Laravel with查询所有字段和查询指定字段
- 查询所有字段
查询单个
Users::with('isLevel')->where('status', '1')->get();
查询多个
Users::with(['isLevel','isApply'])->where('status','1')->get();
其中的isLevel,isApply分别为Users Models中的方法
public function isLevel()
{
return $this->belongsTo('App\Models\Level','level_id', 'id');
}
public function isApply()
{
return $this->belongsTo('App\Models\Apply','apply_id', 'id');
}
- 查询指定字段:
Users::with('isLevel' => function ($query) {
$query->select('name', 'status', 'id');
},'isApply')->where('status','1')->get();
注意:查询指定字段时,要将关联的字段一起查询,否则会报错。