laravel模型使用小技巧

  • Jesse
  • 2019-10-28 15:38:04
  • 5112

laravel模型使用小技巧

1. query

针对 phpstorm 代码提示优化,使用 query

User::query()->find($id)
            ->setAppends([])
            ->makeHidden(['id', 'update_at']);

2. setAppends

有时候在模型里写了 $appends 后,后面查询出的结果里都会出现 $appends 里的字段。 可以通过 setAppends([]) 临时清空 $appends

3. makeHidden

在特定的查询条件或使用场景下不显示指定字段,makeHidden

4. withDefault

模型关联,使用关联的表数据为空时,会报找不到对象的错误,可使用 withDefault,在没有数据时统一返回 null

public function user()
{
    return $this->hasOne(User::class, 'id', 'user_id')->withDefault();
    // 或给一个默认值
    // return $this->hasOne(User::class, 'id', 'user_id')->withDefault(['name' => '佚名']);
}

5. $touches

更新父表的 timestamps
如果需要在更新关联表的同时,更新父表的 timestamps,只需在关联表的 model 中添加 touches 属性

protected $touches = ['parentModel'];

本文出自 ShowCj,转载时请注明出处及相应链接。