我有一个典型的hasMany方法:
public function earmarks() {
return $this->hasMany('App\Earmark');
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用->with('earmarks')检索联接和其他条件时如何为它们添加关系?我要添加:
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
Run Code Online (Sandbox Code Playgroud)
这对我有用
public function earmarks() {
return $this->hasMany('App\Earmark', 'labtop_id', 'id')
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc')->get();
}
Run Code Online (Sandbox Code Playgroud)
它可以是 Labtop 模型中的一个属性,并且可以在 Labtop json 对象中序列化,如下所示:
public function GetEarmarksAttribute() {
return $this->hasMany('App\Earmark', 'labtop_id', 'id')
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc')->get();
}
protected $appends = array('earmarks');
Run Code Online (Sandbox Code Playgroud)
好的,发现我的with()子句中需要一个闭包,如下所示:
$updated_laptops = Laptop::with([
'earmarks' => function($q) {
$q
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
}
])->addJoins()->selectListCols()->find($request->IDs)->keyBy('id');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7681 次 |
| 最近记录: |