Laravel Many-to-one relationship

2019-07-25 01:54发布

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?

1条回答
一纸荒年 Trace。
2楼-- · 2019-07-25 02:31

You have to use hasMany for a one-to-many relation. Your orders function should be like this:

public function orders()
{
    return $this->hasMany('App\Order');
}

The function for status should be belongsTo.

public function status()
{
    return $this->belongsTo('App\Status');
}

belongsToMany is used for many-to-many relation with a pivot table.

查看更多
登录 后发表回答