Friday, March 31, 2017

Laravel Many-to-one relationship

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?



via TheKitMurkit

Advertisement