[英]Laravel many through relation filter using single where condition
我有一组用户,客户和他们是相关的,并且每个月都会改变,我的要求是为客户获得活跃的月份用户。
我的客户模型
public function executives()
{
return $this->belongsToMany(User::class, 'user_customer_mapping', 'user_customer_mapping_customer_id', 'user_customer_mapping_user_id');
}
user_customer_mapping表有一个月份的列,其值为 (Ym),我需要为所有客户找到“2020-10”执行官
$month= '2020-10';
$Executive = $customer->executives()->where('user_farmer_mapping_season', $month)->first();
return ($fieldExecutive) ? $fieldExecutive->name : 'N/A';
首先将withPivot添加到您的关系中,以便还加载其他数据透视表列:
public function executives()
{
return $this->belongsToMany(User::class, 'user_customer_mapping', 'user_customer_mapping_customer_id', 'user_customer_mapping_user_id')
->withPivot('month');
}
接下来,使用wherePivot查询数据透视表列:
$month= '2020-10';
$Executive = $customer->executives()->wherePivot('month', $month)->first();
return ($fieldExecutive) ? $fieldExecutive->name : 'N/A';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.