Laravel多对一关系 [英] Laravel Many-to-one relationship
问题描述
我有两张表:
订单
-id
-status_id
状态
-id
-label
关系是: p>
任何订单都有一个状态
public function status()
{
return $ this-> hasOne('App \Status');
}
任何状态都可以属于许多订单
public function orders()
{
return $ this-> belongsToMany('App \Order');
}
我想是正确的?
现在,如果我使用:
$ o = Status :: with('orders') - >得到();
我得到所有的订单。
如果我使用:
$ o = Order :: with('status') - > get() ;
我收到错误!
未找到列:1054未知列'where子句'中的status.order_id'(SQL:select * from status
其中 status
。 order_id
in(1,2,3,4,5))
但是我没有status.order_id,而是有order.status_id。
如何获取订单状态的标签?像 order-> status-> label ?
你必须使用 hasMany
多关系你的订单函数应该是这样的:
public function orders()
{
return $ this- >的hasMany( 'App\Order');
}
状态的功能
应该是 belongsTo
。
public function status()
{
return $ this- >属于关联( 'App\Status');
}
belongsToMany
用于与枢轴表的多对多关系。
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:
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.
这篇关于Laravel多对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!