疾速入门

更换表名

protected $table = 'my_flights';

更换主键名称

protected $primaryKey  = 'id';

留神: Eloquent 默认主键字段是自增的整型数据, 这意味着主键将会被主动转化为 int 类型, 如果你想要应用非自增或非数字类型主键, 必须在对应模型中设置 $incrementing 属性为 false , 如果主键不是整型, 还要设置 $keyType 属性值为 string.

敞开工夫戳记录

public $timestamps = false;

获取模型数据

// Eloquent 的 all 办法返回模型表的所有后果$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();// 通过传递主键数组来调用 find 办法, 这将会返回匹配记录汇合$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();

软删除

// Eloquent 模型use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\SoftDeletes;class Flight extends Model{    use SoftDeletes;    /**     * 应该被调整为日期的属性     *     * @var array     */    protected $dates = ['deleted_at'];}// 数据表构造增加 deleted_at 列Schema::table('flights', function ($table) {    $table->softDeletes();});// 判断给定模型实例是否被软删除, 能够应用 trashed 办法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();// 应用 restore 办法来疾速复原多个模型, 不会触发任何模型事件App\Flight::withTrashed()    ->where('airline_id', 1)    ->restore();$flight->history()->restore();

本地作用域

/** * 只蕴含沉闷用户的查问作用域 * * @return \Illuminate\Database\Eloquent\Builder */public function scopePopular($query){    return $query->where('votes', '>', 100);}/** * 只蕴含激活用户的查问作用域 * * @return \Illuminate\Database\Eloquent\Builder */public function scopeActive($query){    return $query->where('active', 1);}// 应用本地作用域$users = App\User::popular()->active()->orderBy('created_at')->get();

动静作用域

/** * 让查问只蕴含给定类型的用户 * * @param \Illuminate\Database\Eloquent\Builder $query * @param mixed $type * @return \Illuminate\Database\Eloquent\Builder */public function scopeOfType($query, $type){    return $query->where('type', $type);}// 应用动静作用域$users = App\User::ofType('admin')->get();

模型关联

一对一关联

// 领有class User extends Model{    /**     * 获取关联到用户的手机     */    public function phone()    {        // Phone : 关联的模型        // Phone : user_id 外键        // User  : id      主键        return $this->hasOne('App\Phone', 'user_id', 'id');    }}// 所属class Phone extends Model{    /**     * 获取领有该手机的用户     */    public function user()    {        // User  : 所属的模型        // Phone : user_id 外键        // User  : id      父模型主键        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()    {        // Comment : 关联的模型        // Comment : post_id 外键        // Post    : id      主键        return $this->hasMany('App\Comment', 'post_id', 'id');    }}// 所属class Comment extends Model{    /**     * 获取评论对应的博客文章     */    public function post()    {        // Post    : 关联的模型        // Comment : post_id 外键        // Post    : id      父模型主键        return $this->belongsTo('App\Post', 'post_id', 'id');    }}

多对多关联

// 关联class User extends Model{    /**     * 用户角色     */    public function roles()    {        // Role       : 关联的模型        // user_roles : 两头表名称        // user_id    : 对应到模型主键        // role_id    : 对应到关联主键        return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');    }}// 获取两头表字段, 通过 pivot 属性$user = App\User::find(1);foreach ($user->roles as $role) {    echo $role->pivot->created_at;}// 当 pivot 表蕴含额定的属性时, 必须定义关联时先指定return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');// 主动蕴含created_at 和 updated_atreturn $this->belongsToMany('App\Role')->withTimestamps();// 更换 pivot 为 subscription, 晋升可读性return $this->belongsToMany('App\Podcast')            ->as('subscription')            ->withTimestamps();$users = User::with('podcasts')->get();foreach ($users->flatMap->podcasts as $podcast) {    echo $podcast->subscription->created_at;}

渴求式加载

// select * from books$books = App\Book::all();// select * from authors where id in (1, 2, 3, 4, 5, ...)$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();// 渴求式加载指定字段// 注: 应用这个个性时, id 字段是必须列出的$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);// 调用 comments 办法获取关联关系实例, save 将增加 post_id 到 Comment 模型中$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.']),]);// 应用 create 创立, 与 save 不同的是, 它j接管一个关联数组, create 办法遵循模型属性的批量赋值操作$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.',    ],]);// 更新隶属关联关系 (belongsTo)$account = App\Account::find(10);// associate 办法会在子模型设置外键$user->account()->associate($account);$user->save();// 移除关联 (belongsTo) // dissociate 办法会设置关联关系的外键为 null$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();// attach 和 detach 还接管数组模式的 ID 作为输出$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{    /**     * 获取用户的名字     *     * @param  string  $value     * @return string     */    public function getFirstNameAttribute($value)    {        return ucfirst($value);    }    /**    * 获取用户的全名    *    * @return string    */    public function getFullNameAttribute()    {        return "{$this->first_name} {$this->last_name}";    }}// 拜访 first_name 属性$firstName = App\User::find(1)->first_name;

修改器

class User extends Model{    /**     * 设置用户的名字     *     * @param  string  $value     * @return string     */    public function setFirstNameAttribute($value)    {        $this->attributes['first_name'] = strtolower($value);    }}// 设置 first_name 属性App\User::find(1)->first_name = 'Sally';

日期修改器

默认状况下, Eloquent 将会转化 created_atupdated_at 列的值为 Carbon 实例, 该类继承自 PHP 原生的 Datetime 类, 并提供了各种有用的办法. 你能够自定义哪些字段被主动调整批改, 甚至能够通过重写模型中的 $dates 属性齐全禁止调整:

class User extends Model{    /**     * 应该被调整为日期的属性     *     * @var array     */    protected $dates = [        'created_at',         'updated_at',         'disabled_at'    ];}// 主动转换并存储到数据库中$user = App\User::find(1);$user->disabled_at = Carbon::now();$user->save();// 应用 Carbon 提供的办法$user = App\User::find(1);return $user->disabled_at->getTimestamp();

模型日期格局

默认状况下, 工夫戳的格局是 Y-m-d H:i:s , 能够联合 $dateFormat 属性自定义格局:

class Flight extends Model{    /**     * 模型日期的存储格局     *     * @var string     */    protected $dateFormat = 'U';}

属性转换

反对的转换类型: integer , real , float , double , string , boolean , object , array , collection , date , datetimetimestamp .

如果数据库有一个 JSONTEXT 字段类型蕴含了序列化 JSON, 可应用 array 转换, 将主动进行 序列化反序列化 .

class User extends Model{    /**     * 应该被转化为原生类型的属性     *     * @var array     */    protected $casts = [        // 转换 is_admin 属性: 从 integer (0/1) 转换为 boolean        'is_admin' => 'boolean',        // 拜访 options 属性将会主动从 JSON 反序列化为 PHP 数组        // 设置 options 属性的值时, 给定数组将会主动转化为 JSON 以供存储        'options' => 'array',    ];}// is_admin 属性曾经被转换了:if ($user->is_admin) {    //}// 主动序列化和反序列化$user = App\User::find(1);$options = $user->options;$options['key'] = 'value';$user->options = $options;$user->save();


文章来源于自己博客,公布于 2018-06-10,原文链接:https://imlht.com/archives/152/