快速入门
更换表名
| protected $table = 'my_flights'; |
更换主键名称
| protected $primaryKey = 'id'; |
注意: Eloquent 默认主键字段是自增的整型数据, 这意味着主键将会被自动转化为 int
类型, 如果你想要使用非自增或非数字类型主键, 必须在对应模型中设置 $incrementing
属性为 false
, 如果主键不是整型, 还要设置 $keyType
属性值为 string
.
关闭时间戳记录
| public $timestamps = false; |
获取模型数据
| |
| $flights = App\Flight::all(); |
| |
| foreach ($flights as $flight) { |
| echo $flight->name; |
| } |
| |
| |
| $flights = App\Flight::where('active', 1) |
| ->orderBy('name', 'desc') |
| ->take(10) |
| ->get(); |
获取单个模型
| |
| $flight = App\Flight::find(1); |
| |
| $flight = App\Flight::where('active', 1)->first(); |
| |
| $flights = App\Flight::find([1, 2, 3]); |
获取聚合结果
| $count = App\Flight::where('active', 1)->count(); |
| $max = App\Flight::where('active', 1)->max('price'); |
插入记录
| $flight = new Flight; |
| $flight->name = $request->name; |
| $flight->save(); |
更新模型
| $flight = App\Flight::find(1); |
| $flight->name = 'New Flight Name'; |
| $flight->save(); |
批量更新
| App\Flight::where('active', 1) |
| ->where('destination', 'San Diego') |
| ->update(['delayed' => 1]); |
删除模型
| |
| $flight = App\Flight::find(1); |
| $flight->delete(); |
| |
| |
| App\Flight::destroy(1); |
| App\Flight::destroy([1, 2, 3]); |
| App\Flight::destroy(1, 2, 3); |
| |
| |
| $deletedRows = App\Flight::where('active', 0)->delete(); |
软删除
| |
| use Illuminate\Database\Eloquent\Model; |
| use Illuminate\Database\Eloquent\SoftDeletes; |
| class Flight extends Model |
| { |
| use SoftDeletes; |
| |
| |
| |
| |
| |
| protected $dates = ['deleted_at']; |
| } |
| |
| |
| Schema::table('flights', function ($table) { |
| $table->softDeletes(); |
| }); |
| |
| |
| if ($flight->trashed()) { |
| |
| } |
| |
| |
| $flights = App\Flight::withTrashed() |
| ->where('account_id', 1) |
| ->get(); |
| $flight->history()->withTrashed()->get(); |
| |
| |
| $flights = App\Flight::onlyTrashed() |
| ->where('airline_id', 1) |
| ->get(); |
| |
| |
| $flight->restore(); |
| |
| |
| App\Flight::withTrashed() |
| ->where('airline_id', 1) |
| ->restore(); |
| $flight->history()->restore(); |
本地作用域
| |
| |
| |
| |
| |
| public function scopePopular($query) |
| { |
| return $query->where('votes', '>', 100); |
| } |
| |
| |
| |
| |
| |
| |
| public function scopeActive($query) |
| { |
| return $query->where('active', 1); |
| } |
| |
| $users = App\User::popular()->active()->orderBy('created_at')->get(); |
动态作用域
| |
| |
| |
| |
| |
| |
| |
| public function scopeOfType($query, $type) |
| { |
| return $query->where('type', $type); |
| } |
| |
| $users = App\User::ofType('admin')->get(); |
模型关联
一对一关联
| |
| class User extends Model |
| { |
| |
| |
| |
| public function phone() |
| { |
| |
| |
| |
| return $this->hasOne('App\Phone', 'user_id', 'id'); |
| } |
| } |
| |
| |
| class Phone extends Model |
| { |
| |
| |
| |
| public function user() |
| { |
| |
| |
| |
| return $this->belongsTo('App\User', 'user_id', 'id'); |
| } |
| } |
| |
| |
| class Article extends Model |
| { |
| |
| |
| |
| public function user() |
| { |
| return $this->belongsTo('App\User')->withDefault(function ($user) { |
| $user->name = 'Guest Author'; |
| }); |
| } |
| } |
一对多关联
| |
| class Post extends Model |
| { |
| |
| |
| |
| public function comments() |
| { |
| |
| |
| |
| return $this->hasMany('App\Comment', 'post_id', 'id'); |
| } |
| } |
| |
| |
| class Comment extends Model |
| { |
| |
| |
| |
| public function post() |
| { |
| |
| |
| |
| return $this->belongsTo('App\Post', 'post_id', 'id'); |
| } |
| } |
多对多关联
| |
| class User extends Model |
| { |
| |
| |
| |
| public function roles() |
| { |
| |
| |
| |
| |
| return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id'); |
| } |
| } |
| |
| |
| $user = App\User::find(1); |
| foreach ($user->roles as $role) { |
| echo $role->pivot->created_at; |
| } |
| |
| |
| return $this->belongsToMany('App\Role')->withPivot('column1', 'column2'); |
| |
| |
| return $this->belongsToMany('App\Role')->withTimestamps(); |
| |
| |
| return $this->belongsToMany('App\Podcast') |
| ->as('subscription') |
| ->withTimestamps(); |
| $users = User::with('podcasts')->get(); |
| foreach ($users->flatMap->podcasts as $podcast) { |
| echo $podcast->subscription->created_at; |
| } |
渴求式加载
| |
| $books = App\Book::all(); |
| |
| $books = App\Book::with('author')->get(); |
| foreach ($books as $book) { |
| echo $book->author->name; |
| } |
| |
| |
| $books = App\Book::with('author', 'publisher')->get(); |
| |
| |
| $books = App\Book::with('author.contacts')->get(); |
| |
| |
| |
| $users = App\Book::with('author:id,name')->get(); |
| |
| |
| $users = App\User::with(['posts' => function ($query) { |
| $query->where('title', 'like', '%first%'); |
| }])->get(); |
插入 / 更新关联模型
| |
| $comment = new App\Comment(['message' => 'A new comment.']); |
| $post = App\Post::find(1); |
| |
| $post->comments()->save($comment); |
| |
| |
| $post = App\Post::find(1); |
| $post->comments()->saveMany([ |
| new App\Comment(['message' => 'A new comment.']), |
| new App\Comment(['message' => 'Another comment.']), |
| ]); |
| |
| |
| $post = App\Post::find(1); |
| $comment = $post->comments()->create([ |
| 'message' => 'A new comment.', |
| ]); |
| |
| |
| $post = App\Post::find(1); |
| $post->comments()->createMany([ |
| [ |
| 'message' => 'A new comment.', |
| ], |
| [ |
| 'message' => 'Another new comment.', |
| ], |
| ]); |
| |
| |
| $account = App\Account::find(10); |
| |
| $user->account()->associate($account); |
| $user->save(); |
| |
| |
| |
| $user->account()->dissociate(); |
| $user->save(); |
附加 / 分离多对多关联模型
| $user = App\User::find(1); |
| |
| $user->roles()->attach($roleId); |
| |
| $user->roles()->attach($roleId, ['expires' => $expires]); |
| |
| |
| $user->roles()->detach($roleId); |
| |
| $user->roles()->detach(); |
| |
| |
| $user = App\User::find(1); |
| $user->roles()->detach([1, 2, 3]); |
| $user->roles()->attach([ |
| 1 => ['expires' => $expires], |
| 2 => ['expires' => $expires] |
| ]); |
在中间表上保存额外数据
处理多对多关联时, save
方法接收中间表数组作为第二个参数:
| App\User::find(1)->roles()->save($role, ['expires' => $expires]); |
访问器和修改器
访问器和修改器
允许你在获取模型属性或设置其值时格式化 Eloquent
属性.
例如, 你可能想要使用 Laravel
加密器对存储在数据库中的数据进行加密, 并且在 Eloquent
模型中访问时自动进行解密.
除了自定义访问器和修改器, Eloquent
还可以自动转换日期字段为 Carbon
实例甚至 将文本转换为 JSON
.
访问器
| class User extends Model |
| { |
| |
| |
| |
| |
| |
| |
| public function getFirstNameAttribute($value) |
| { |
| return ucfirst($value); |
| } |
| |
| |
| |
| |
| |
| |
| public function getFullNameAttribute() |
| { |
| return "{$this->first_name} {$this->last_name}"; |
| } |
| } |
| |
| $firstName = App\User::find(1)->first_name; |
修改器
| class User extends Model |
| { |
| |
| |
| |
| |
| |
| |
| public function setFirstNameAttribute($value) |
| { |
| $this->attributes['first_name'] = strtolower($value); |
| } |
| } |
| |
| App\User::find(1)->first_name = 'Sally'; |
日期修改器
默认情况下, Eloquent
将会转化 created_at
和 updated_at
列的值为 Carbon 实例, 该类继承自 PHP
原生的 Datetime
类, 并提供了各种有用的方法. 你可以自定义哪些字段被自动调整修改, 甚至可以通过重写模型中的 $dates
属性完全禁止调整:
| class User extends Model |
| { |
| |
| |
| |
| |
| |
| protected $dates = [ |
| 'created_at', |
| 'updated_at', |
| 'disabled_at' |
| ]; |
| } |
| |
| |
| $user = App\User::find(1); |
| $user->disabled_at = Carbon::now(); |
| $user->save(); |
| |
| |
| $user = App\User::find(1); |
| return $user->disabled_at->getTimestamp(); |
模型日期格式
默认情况下, 时间戳的格式是 Y-m-d H:i:s
, 可以结合 $dateFormat
属性自定义格式:
| class Flight extends Model |
| { |
| |
| |
| |
| |
| |
| protected $dateFormat = 'U'; |
| } |
属性转换
支持的转换类型: integer
, real
, float
, double
, string
, boolean
, object
, array
, collection
, date
, datetime
和 timestamp
.
如果数据库有一个 JSON
或 TEXT
字段类型包含了序列化 JSON
, 可使用 array
转换, 将自动进行 序列化
和 反序列化
.
| class User extends Model |
| { |
| |
| |
| |
| |
| |
| protected $casts = [ |
| |
| 'is_admin' => 'boolean', |
| |
| |
| 'options' => 'array', |
| ]; |
| } |
| |
| |
| if ($user->is_admin) { |
| |
| } |
| |
| |
| $user = App\User::find(1); |
| $options = $user->options; |
| $options['key'] = 'value'; |
| $user->options = $options; |
| $user->save(); |
文章来源于本人博客,发布于 2018-06-02,原文链接:https://imlht.com/archives/152/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?