laravel之Eloquent ORM

Eloquent 模型,功能强大的查询构建器

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
    //自定义用于存储时间戳的字段名称
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'last_update';

    public $primaryKey = 'x_id'; //覆盖默认主键 id 
    protected $table = 'my_flights';  //关联到模型的数据表

    public $timestamps = false;  //不打时间戳, 不更新created_at 和 updated_at
    protected $dateFormat = 'U';  //模型日期列的存储格式
    protected $connection = 'connection-name';
    protected $fillable = ['name']; // 可以被批量赋值的属性.
    protected $guarded = ['price']; // 不能被批量赋值的属性

    protected $dates = ['deleted_at'];  //应该被调整为日期的属性
}

获取单个模型/聚合结果

App\Flight::find(1);
App\Flight::where('active', 1)->first();
App\Flight::find([1, 2, 3]);

Not Found 异常

$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();

聚合结果

$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]);

 

create

firstOrCreate/firstOrNew

// 通过属性获取航班, 如果不存在则创建...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
// 通过name获取航班,如果不存在则通过name和delayed属性创建...
$flight = App\Flight::firstOrCreate(
   ['name' => 'Flight 10'], ['delayed' => 1]
);

// 通过属性获取航班, 如果不存在初始化一个新的实例…

$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

// 通过name获取,如果不存在则通过name和delayed属性创建新实例…

$flight = App\Flight::firstOrNew(
['name' => 'Flight 10'], ['delayed' => 1]
);

updateOrCreate

// 如果有从奥克兰到圣地亚哥的航班则将价格设置为 $99
// 如果没有匹配的模型则创建之
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);

删除模型

$flight = App\Flight::find(1);
$flight->delete();

通过主键删除模型

App\Flight::destroy(1);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(1, 2, 3);

通过查询删除模型

App\Flight::where('active', 0)->delete();

软删除

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

判断给定模型实例是否被软删除,可以使用 trashed 方法:

if ($flight->trashed()) {
//
}

包含软删除模型

App\Flight::withTrashed()
->where('account_id', 1)
->get();

只获取软删除模型

App\Flight::onlyTrashed()
->where('airline_id', 1)
->get();

恢复软删除模型

$flight->restore();

使用 restore 方法来快速恢复多个模型

App\Flight::withTrashed()
->where('airline_id', 1)
->restore();

永久删除模型

// 强制删除单个模型实例...
$flight->forceDelete();
// 强制删除所有关联模型...
$flight->history()->forceDelete();

 

查询作用域

Scope 接口

匿名的全局作用域

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class User extends Model{
protected static function boot()
{
      parent::boot();

      static::addGlobalScope('age', function(Builder $builder) {
          $builder->where('age', '>', 200);
      });
    }
}

移除全局作用域

User::withoutGlobalScope(AgeScope::class)->get();

// 移除所有全局作用域

User::withoutGlobalScopes()->get();

//移除某些全局作用域

User::withoutGlobalScopes([FirstScope::class, SecondScope::class])->get();

本地作用域
Model类写 scope 开头的方法

public function scopePopular($query)
{
    return $query->where('votes', '>', 100);
}

使用本地作用域

App\User::popular()->active()->orderBy('created_at')->get();

动态作用域,可以接受参数

public function scopeOfType($query, $type){
    return $query->where('type', $type);
}

事件

Eloquent 模型可以触发事件,允许你在模型生命周期中的多个时间点调用如下这些方法:retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored。

protected $dispatchesEvents = [
    'saved' => UserSaved::class,
    'deleted' => UserDeleted::class,
];

定义观察者 App\Observers
注册观察者: App\Providers\AppServiceProvider ;

 

访问器 & 修改器

定义访问器

public function getFirstNameAttribute($value)
{
return ucfirst($value);
}

定义修改器
setFirstNameAttribute

属性转换
常用属性:integer, real, float, double, string, boolean, object,array,collection,date,datetime 和 timestamp
protected $casts = [
‘is_admin’ => ‘boolean’,
];

日期修改器
protected $dates = [ ‘created_at’, ‘updated_at’, ‘disabled_at’];
日期格式化
protected $dateFormat = ‘U’;