Laravel许多一对一的关系
问题描述:
我有两个表:Laravel许多一对一的关系
orders
-id
-status_id
status
-id
-label
的关系是:
任何订单都有一个状态
public function status()
{
return $this->hasOne('App\Status');
}
任何状态可以属于很多订单
public function orders()
{
return $this->belongsToMany('App\Order');
}
我想它是c orrect?现在
,如果我使用:
$o = Status::with('orders')->get();
我得到的所有订单。 如果我使用:
$o = Order::with('status')->get();
我得到一个错误! 未找到列:1054'where子句'中的未知列'status.order_id'(SQL:select * from status
where status
。order_id
in(1,2,3,4,5)) 但我没有状态.order_id,而我有order.status_id。
如何获得订单状态的标签?像order-> status-> label?
答
您必须使用hasMany
作为一对多关系。您的订单功能应该是这样的:
public function orders()
{
return $this->hasMany('App\Order');
}
为status
的功能应该是belongsTo
。
public function status()
{
return $this->belongsTo('App\Status');
}
belongsToMany
用于与数据透视表的多对多关系。