hyperf 數據庫模型-model操作


生成model

php bin/hyperf.php gen:model user

User model app/Model/User.php

<?php

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

use Hyperf\DbConnection\Model\Model;
/**
 */
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 = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];

    /**
     * 不自動維護時間戳
     * @var bool
     */
    public $timestamps = false;
}

模型成員變量

參數    類型    默認值    備注
connection    string    default    數據庫連接
table    string    無    數據表名稱
primaryKey    string    id    模型主鍵
keyType    string    int    主鍵類型
fillable    array    []    允許被批量賦值的屬性
casts    string    無    數據格式化配置
timestamps    bool    true    是否自動維護時間戳
incrementing    bool    true    是否自增主鍵

模型查詢

use App\Model\User;

$user = User::query()->where('id', 1)->first();
$user = User::query()->where('id', 1)->find(1);
$freshUser = $user->fresh();

$count = User::query()->where('age', 23)->count();

插入

use App\Model\User;

$user = new User();
$user->name = 'xiaohong';
$user->age = 23;
$bool = $user->save();

更新

$user = User::query()->where('id', 1)->find(1);
$user->name = 'xiaohong';
$user->age = 23;
$bool = $user->save();

批量更新

User::query()->where('age', 23)->update(['age' => '24']);

刪除

User::query()->where('id', 3)->delete();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM