【发布时间】:2016-03-14 22:18:52
【问题描述】:
我正在编写代码来获取 Laravel 中的嵌套对象。我想知道是否可以在 hasMany 或 belongsTo 中编写条件。
这就是我正在做的事情,这使问题变得清晰:
$posts = Post::where(
array(
'status' => 'active'
)
)
->orderBy('id', 'asc')
->with(['postResponsibilities' => function($query){
$query->where('status', 'active');
}])
->with(['postRequirements' => function($query){
$query->where('status', 'active');
}])
->with(['postSalaries' => function($query){
$query->where('status', 'active');
}])
->skip($limit * ($page - 1))->take($limit)->get();
所以,我必须使用嵌套查询来仅获取那些 status 为 active 的记录。
在 Post 模型中,我写了:
public function postRequirements(){
return $this->hasMany('App\Models\PostRequirement', 'post_id');
}
public function postResponsibilities(){
return $this->hasMany('App\Models\PostResponsibility', 'post_id');
}
public function postSalaries(){
return $this->hasMany('App\Models\PostSalary', 'post_id');
}
有没有办法可以在嵌套模型中定义状态条件? 这样我就可以写了:
$posts = Post::where(
array(
'status' => 'active'
)
)
->orderBy('id', 'asc')
->with('postResponsibilities')
->with('postRequirements')
->with('postSalaries')
->skip($limit * ($page - 1))->take($limit)->get();
希望问题清楚,谢谢
【问题讨论】: