2017-03-31 122 views
0

我有两个表: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 statusorder_id in(1,2,3,4,5)) 但我没有状态.order_id,而我有order.status_id。

如何获得订单状态的标签?像order-> status-> label

回答

2

您必须使用hasMany作为一对多关系。您的订单功能应该是这样的:

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

status的功能应该是belongsTo

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

belongsToMany用于与数据透视表的多对多关系。