[英]Laravel eloquent builder, 3 tables with relations
I have 3 models that are: contracts
, centers
and user_centers
. 我有3个型号是: contracts
, centers
和user_centers
。
The relationship between contracts
and centers
is 1 to N (1 center has N contracts) contracts
与centers
之间的关系是1到N(1个中心有N个合同)
And the relation between centers
and user_centers
, is 1 center has N user_centers
. 之间的关系centers
和user_centers
,是1个中心有N个user_centers
。
I'm trying to eloquent a function that returns contracts by filtering by a user_id
( user_centers
table) 我正在尝试雄辩的功能是通过按user_id
( user_centers
表)进行过滤来返回合同
For that I do the following 为此,我执行以下操作
$query = Contract::query();
$user_id = $request->query('userId');
$query->when(request('user_id'), function ($q) use ($user_id) {
$q->whereHas('centers.user_centers', function ($q) use ($user_id) {
$q->where('user_id', $user_id);
});
});
This does not work and I do not know if I have not understood the relationship or eloquent. 这是行不通的,我不知道我是否不了解这种关系或雄辩。
Thank you 谢谢
Just add a function on modal 只需在模态上添加一个函数
class Contracts extends Model {
...
public function centres()
{
$this->hasMany(Centres::class, 'centre_id', 'id');
}
}
When for 1 centers with many user_centres use this function in model: 当有许多user_centres的1个中心在模型中使用此功能时:
class Centers extends Model {
...
public function user_centers()
{
$this->hasMany(user_centers::class, 'user_centers_id', 'id');
}
}
and eloquent : 和雄辩:
Contract::with('centres')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.