hyperf数组模型化

databases.php配置
return [
    'default' => [
        'driver'    => env('DB_DRIVER', 'mysql'),
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'hyperf'),
        'port'      => env('DB_PORT', 3306),
        'username'  => env('DB_USERNAME', 'root'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => env('DB_CHARSET', 'utf8'),
        'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
        'prefix'    => env('DB_PREFIX', ''),
        'pool'      => [
            'min_connections' => 1,
            'max_connections' => 10,
            'connect_timeout' => 10.0,
            'wait_timeout'    => 3.0,
            'heartbeat'       => -1,
            'max_idle_time'   => (float)env('DB_MAX_IDLE_TIME', 60),
        ],
        'commands'  => [
            'gen:model' => [
                'path'             => 'app/Model',
                'force_casts'      => true,
                'inheritance'      => 'Model',
                'refresh_fillable' => true,// 是否刷新 fillable 参数
                'with_comments'    => true,// 是否增加字段注释
            ],
        ],
    ],
];
生成模型文件命令
php bin/hyperf.php gen:model company
Company.php
<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Model\Model;
/**
 * @property int $fid ID
 * @property string $fcompany 公司名称
 * @property string $creation_date 新增日期
 * @property string $last_update 修改日期
 */
class Company extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'company';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['fid', 'fcompany', 'creation_date', 'last_update'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['fid' => 'integer'];
}

TestModel.php
<?php

namespace App\Model;

/**
 * @property string $name
 * @property string $sex
 */
class TestModel extends Model
{
    protected $fillable = ['name','sex'];
}

 

json -> array -> model 
$json = '{"name":"远思软件","sex":"女"}';
$arrJson = json_decode($json, true);
$testModel = new TestModel($arrJson);
var_dump($testModel->name);

 其它操作示例

// 判断账号是否存在,存在返回true
public function isExits($params): bool
{
    $this->validateParams($params, [
        'fusername' => 'required',
    ], [
        'fusername.required' => '登录账号不能为空',
    ]);

    $userParams = new User($params);
    $user = User::query()->where([
        'fusername' => $userParams->fusername,
    ])->first();

    return !empty($user);

}

 

posted @ 2022-04-24 22:29  lobtao  阅读(268)  评论(0)    收藏  举报