我有一个名为company_team
的关系表它与company
和user
的关系,并且在is_ceo
表中有一个字段company_team
来标记公司团队成员是首席执行官的天气。以下是我的模型定义
class CompanyTeam extends Pivot
{
/**
* return all company team member with out ceo
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function team_member()
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* return only ceo's info
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function company_ceo()
{
$this->where('is_ceo', 1); // it dosen't work, but it is effect l want
return $this->belongsTo(User::class, 'user_id');
}
}
我使用addGlobalScope
搜索答案,但它不适合我,因为当我同时使用team_member
和company_ceo
关系时,它会在两者上添加条件
定义关系时无法添加条件。您必须在执行查询时添加条件。
CompanyTeam::with(['company_ceo' => function ($q) use() {
$q->where('is_ceo', 1);
}])
->get();
public function company_ceo()
{
return $this->belongsTo(User::class, 'user_id')->where('is_ceo', 1);
}
我希望这有帮助。有一个美好的一天,快乐的编码...... :)
在用户模型中,您可以定义范围
public function scopeCompanyCeo($query){
return $query->where('is_ceo',1);
}
那么你可以在你的控制器中使用
$user = User::find(1)->companyCeo()->get();