[英]laravel: how to use wherePivot in one to many relationship
I have two one to many pairs: 我有两对一对:
status > orders 状态>订单
status > tickets 状态>票
orders 命令
id, status_id
1, 5
tickets 车票
id, status_id
1, 2
statuses 状态
id, table, language_id, key, name
1, 'orders', 1, 1, 'Pending'
2, 'orders', 1, 2, 'Processing'
3, 'orders', 1, 3, 'Shipped'
4, 'orders', 1, 4, 'Canceled'
5, 'orders', 1, 5, 'Complete'
6, 'tickets', 1, 1, 'unanswered'
7, 'tickets', 1, 2, 'answered'
8, 'tickets', 1, 3, 'closed'
//unique(['table', 'language_id', 'key'])
In Order Model 订单模型
public function status()
{
//ok
return $this->belongsTo('App\Models\Status', 'status_id', 'key')->where('table', 'orders')->where('language_id', 1);
//not ok
return $this->belongsTo('App\Models\Status', 'status_id', 'key')->wherePivot('table', '=', 'orders')->wherePivot('language_id', '=', 1);
}
Controller 控制者
$order = \App\Models\Order::find(1);
dd($order->status);
Error message: Column not found: 1054 Unknown column 'pivot' in 'where clause' (SQL: select * from statuses
where statuses
. key
= 5 and pivot
= table and pivot
= language_id limit 1) 未发现柱::错误消息1054未知列“枢轴”在“where子句”(SQL:SELECT * FROM
statuses
,其中statuses
。 key
= 5和pivot
=表和pivot
= LANGUAGE_ID极限1)
If where() is ok, why there is wherePivot()? 如果where()可以,为什么会有wherePivot()?
How to use wherePivot correctly? 如何正确使用wherePivot?
First of all, the relationship between Order and Status should be better defined in a different table like 'order_status' and relationship between tickets and status be in a table 'ticket_status' 首先,应该在不同的表(例如“ order_status”)中更好地定义“订单”和“状态”之间的关系,而在“ ticket_status”表中,票证与状态之间的关系
Then you should rather define the relationship like this: 然后,您应该这样定义关系:
In the Order Model 在订单模型中
public function status()
{
return $this->belongsToMany('App\Status', 'order_status’, status_id', ‘order_id’)->withPivot('language_id');
}
Then call it like this: 然后这样称呼它:
App\Order::find(1)->status()->wherePivot(‘language_id’, 1)->get();
Hope it works.. Typing from my phone 希望它能工作..用我的手机打字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.