2022-10-31 01:47:12 +08:00
# Model creation script
2022-02-16 02:13:55 +08:00
2022-11-15 12:01:53 +08:00
Hyperf provides commands to create models, and you can easily create corresponding models based on data tables. The command generates the model via `AST` , so when you add certain methods, you can also easily reset the model with the script.
2022-02-16 02:13:55 +08:00
```bash
php bin/hyperf.php gen:model table_name
```
2022-10-11 02:23:33 +08:00
## Create a model
2022-02-16 02:13:55 +08:00
2022-10-11 02:23:33 +08:00
The optional parameters are as follows:
2022-02-16 02:13:55 +08:00
2022-11-15 12:01:53 +08:00
| Parameter | Type | Defaults | Remark |
|:------------------:|:------:|:---------------------------------:|:----------------------------------------------------------------------------------------------:|
| --pool | string | `default` | Connection pool, the script will be created based on the current connection pool configuration |
| --path | string | `app/Model` | model path |
| --force-casts | bool | `false` | Whether to force reset the `casts` parameter |
| --prefix | string | empty string | table prefix |
| --inheritance | string | `Model` | The parent class |
| --uses | string | `Hyperf\DbConnection\Model\Model` | Use with `inheritance` |
| --refresh-fillable | bool | `false` | Whether to refresh the `fillable` parameter |
| --table-mapping | array | `[]` | Add a mapping relationship for table name -> model such as ['users:Account'] |
| --ignore-tables | array | `[]` | There is no need to generate the table name of the model e.g. ['users'] |
| --with-comments | bool | `false` | Whether to add field comments |
| --property-case | int | `0` | Field Type: 0 Snakecase, 1 CamelCase |
2022-02-16 02:13:55 +08:00
2022-10-31 01:47:12 +08:00
When using `--property-case` to convert the field type to camel case, you also need to manually add `Hyperf\Database\Model\Concerns\CamelCase` to the model.
The corresponding configuration can also be configured in `databases.{pool}.commands.gen:model` , as follows
2022-02-16 02:13:55 +08:00
2022-11-15 12:01:53 +08:00
> All struck-through need to be converted to underscores
2022-02-16 02:13:55 +08:00
```php
< ?php
declare(strict_types=1);
use Hyperf\Database\Commands\ModelOption;
return [
'default' => [
2022-10-31 01:47:12 +08:00
// Ignore other configurations
2022-02-16 02:13:55 +08:00
'commands' => [
'gen:model' => [
'path' => 'app/Model',
'force_casts' => true,
'inheritance' => 'Model',
'uses' => '',
'refresh_fillable' => true,
'table_mapping' => [],
'with_comments' => true,
'property_case' => ModelOption::PROPERTY_SNAKE_CASE,
],
],
],
];
```
2022-10-31 01:47:12 +08:00
The created model is as follows
2022-02-16 02:13:55 +08:00
```php
< ?php
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
/**
* @property $id
* @property $name
* @property $gender
* @property $created_at
* @property $updated_at
*/
class User extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['id', 'name', 'gender', 'created_at', 'updated_at'];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = ['id' => 'integer', 'gender' => 'integer'];
}
```
## Visitors
2022-10-31 01:47:12 +08:00
The framework provides several `Visitors` for users to extend the scripting capabilities. The usage is very simple, just add the corresponding `Visitor` in the `visitors` configuration.
2022-02-16 02:13:55 +08:00
```php
< ?php
declare(strict_types=1);
return [
'default' => [
2022-10-31 01:47:12 +08:00
// Ignore other configurations
2022-02-16 02:13:55 +08:00
'commands' => [
'gen:model' => [
'visitors' => [
Hyperf\Database\Commands\Ast\ModelRewriteKeyInfoVisitor::class
],
],
],
],
];
```
2022-10-31 01:47:12 +08:00
### Optional Visitors
2022-02-16 02:13:55 +08:00
- Hyperf\Database\Commands\Ast\ModelRewriteKeyInfoVisitor
2022-10-31 01:47:12 +08:00
This `Visitor` can generate the corresponding `$incrementing` `$primaryKey` and `$keyType` according to the primary key in the database.
2022-02-16 02:13:55 +08:00
- Hyperf\Database\Commands\Ast\ModelRewriteSoftDeletesVisitor
2022-10-31 01:47:12 +08:00
This `Visitor` can judge whether the model contains soft delete fields according to the `DELETED_AT` constant, and if so, add the corresponding Trait `SoftDeletes` .
2022-02-16 02:13:55 +08:00
- Hyperf\Database\Commands\Ast\ModelRewriteTimestampsVisitor
2022-10-31 01:47:12 +08:00
This `Visitor` can automatically determine, based on `created_at` and `updated_at` , whether to enable the default recording of `created and modified times` .
2022-02-16 02:13:55 +08:00
- Hyperf\Database\Commands\Ast\ModelRewriteGetterSetterVisitor
2022-10-31 01:47:12 +08:00
This `Visitor` can generate corresponding `getters` and `setters` based on database fields.
2022-02-16 02:13:55 +08:00
2022-10-31 01:47:12 +08:00
## Override Visitor
2022-02-16 02:13:55 +08:00
2022-10-31 01:47:12 +08:00
In the Hyperf framework, when `gen:model` is used, `decimal` is converted to `float` by default. as follows:
2022-02-16 02:13:55 +08:00
```php
< ?php
declare(strict_types=1);
namespace App\Model;
/**
* @property int $id
* @property int $count
* @property float $float_num // decimal
* @property string $str
* @property string $json
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
class UserExt extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_ext';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['id', 'count', 'float_num', 'str', 'json', 'created_at', 'updated_at'];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = ['id' => 'integer', 'count' => 'integer', 'float_num' => 'float', 'created_at' => 'datetime', 'updated_at' => 'datetime'];
}
```
2022-10-31 01:47:12 +08:00
At this point, we can modify this feature by overriding `ModelUpdateVisitor` .
2022-02-16 02:13:55 +08:00
```php
< ?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Kernel\Visitor;
use Hyperf\Database\Commands\Ast\ModelUpdateVisitor as Visitor;
use Hyperf\Utils\Str;
class ModelUpdateVisitor extends Visitor
{
protected function formatDatabaseType(string $type): ?string
{
switch ($type) {
case 'tinyint':
case 'smallint':
case 'mediumint':
case 'int':
case 'bigint':
return 'integer';
case 'decimal':
2022-10-31 01:47:12 +08:00
// Set to decimal, and set the corresponding precision
2022-02-16 02:13:55 +08:00
return 'decimal:2';
case 'float':
case 'double':
case 'real':
return 'float';
case 'bool':
case 'boolean':
return 'boolean';
default:
return null;
}
}
protected function formatPropertyType(string $type, ?string $cast): ?string
{
if (! isset($cast)) {
$cast = $this->formatDatabaseType($type) ?? 'string';
}
switch ($cast) {
case 'integer':
return 'int';
case 'date':
case 'datetime':
return '\Carbon\Carbon';
case 'json':
return 'array';
}
if (Str::startsWith($cast, 'decimal')) {
2022-10-31 01:47:12 +08:00
// If cast is decimal, @property is changed to string
2022-02-16 02:13:55 +08:00
return 'string';
}
return $cast;
}
}
```
2022-10-31 01:47:12 +08:00
Configure the mapping relationship `dependencies.php`
2022-02-16 02:13:55 +08:00
```php
< ?php
return [
Hyperf\Database\Commands\Ast\ModelUpdateVisitor::class => App\Kernel\Visitor\ModelUpdateVisitor::class,
];
```
2022-10-31 01:47:12 +08:00
After re-executing `gen:model` , the corresponding model is as follows:
2022-02-16 02:13:55 +08:00
```php
< ?php
declare (strict_types=1);
namespace App\Model;
/**
* @property int $id
* @property int $count
* @property string $float_num
* @property string $str
* @property string $json
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
class UserExt extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_ext';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['id', 'count', 'float_num', 'str', 'json', 'created_at', 'updated_at'];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = ['id' => 'integer', 'count' => 'integer', 'float_num' => 'decimal:2', 'created_at' => 'datetime', 'updated_at' => 'datetime'];
}
```