Reputation: 317
I have set of users, customers and they are related, and it will change every month, my requirement is get active month user for customers.
My Customer Model
public function executives()
{
return $this->belongsToMany(User::class, 'user_customer_mapping', 'user_customer_mapping_customer_id', 'user_customer_mapping_user_id');
}
user_customer_mapping table have a Column for month with values like (Y-m), i need to find "2020-10" executive for all customers
$month= '2020-10';
$Executive = $customer->executives()->where('user_farmer_mapping_season', $month)->first();
return ($fieldExecutive) ? $fieldExecutive->name : 'N/A';
Upvotes: 0
Views: 67
Reputation: 18187
Start by adding withPivot to your relationship so the additional pivot table columns are loaded also:
public function executives()
{
return $this->belongsToMany(User::class, 'user_customer_mapping', 'user_customer_mapping_customer_id', 'user_customer_mapping_user_id')
->withPivot('month');
}
Next, use wherePivot to query against the pivot table column(s):
$month= '2020-10';
$Executive = $customer->executives()->wherePivot('month', $month)->first();
return ($fieldExecutive) ? $fieldExecutive->name : 'N/A';
Upvotes: 1