I have two tables:
orders
-id
-status_id
status
-id
-label
Relations are:
Any Order has one status
public function status()
{
return $this->hasOne('App\Status');
}
Any Status can belong to many orders
public function orders()
{
return $this->belongsToMany('App\Order');
}
I suppose it is correct?
Now,if I use:
$o = Status::with('orders')->get();
I get all the orders. If I use:
$o = Order::with('status')->get();
I get an error!
Column not found: 1054 Unknown column 'status.order_id' in 'where clause' (SQL: select * from status
where status
.order_id
in (1, 2, 3, 4, 5))
But I don't have status.order_id, instead I have order.status_id.
How do I get the label of order's status? Like order->status->label?
You have to use
hasMany
for a one-to-many relation. Your orders function should be like this:The function for
status
should bebelongsTo
.belongsToMany
is used for many-to-many relation with a pivot table.