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)
If where() is ok, why there is wherePivot()?
How to use wherePivot correctly?
Try to querying the result just like that :
dd($order->status()->where('language_id', 1));
You can also use a custom method in your model.
There is a package dedicated for those stuffs: Tinker
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'
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.