Reputation: 1175
I have a relation table named company_team
it relation to company
and user
, and there is a field is_ceo
in company_team
table to flag weather a company team member is an ceo. following is my model define
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');
}
}
l searched an answer with using addGlobalScope
, but it doesn't fit me, because when l use both of team_member
and company_ceo
relation, it will add condition on both of then
Upvotes: 0
Views: 129
Reputation: 312
In user model, you can define a scope
public function scopeCompanyCeo($query){
return $query->where('is_ceo',1);
}
then you can use like in your controller
$user = User::find(1)->companyCeo()->get();
Upvotes: 1
Reputation: 271
public function company_ceo()
{
return $this->belongsTo(User::class, 'user_id')->where('is_ceo', 1);
}
I hope this helps. Have a great day and happy coding... :)
Upvotes: 0
Reputation: 232
You can't add conditions when defining the relationship. You have to add the condition when performing the queries.
CompanyTeam::with(['company_ceo' => function ($q) use() {
$q->where('is_ceo', 1);
}])
->get();
Upvotes: 0