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('sex','男')->get();
注意:查詢指定字段時,要將關聯的字段一起查詢,可能會報錯。