Laravel属于使用'with'时返回null [英] Laravel belongsTo returning null when using 'with'
问题描述
我有一个用户
和订单
型号,用户有很多订单:
#内部用户模型
public function orders(){
$ this-> hasMany('Order');
}
#内部订单
public function user(){
return $ this-> belongsTo('User');
}
//不确定这是否令人烦恼(也可以在订单中)
public function products(){
return $ this-> belongsToMany('产品');
}
所以我想我有上述权利。
但是当我这样做:
$ users = User :: with('orders') - >发现(1);
返回$用户;
我得到调用成员函数addEagerConstraints()on null
。
但是,如果我做的另一回事,它的效果很好:
$ orders = Order :: with('User') - > get();
return $ orders;
我做错了什么/我什么不明白?或者我的问题比我想象的更大?
数据库:
问题是你没有返回
为您的订单
关系。应该是:
public function orders(){
return $ this-> hasMany('Order') ;
}
您还应该使用您的关系区分大小写。你显示:
$ orders = Order :: with('User') - > get();
正在工作,但您应该使用
$ orders = Order :: with('user') - > get();
以避免将来对数据库的额外查询
I'm just getting started with Laravel so please forgive any noobness.
I have a User
and Order
model, a user has many orders:
# Inside User model
public function orders(){
$this->hasMany('Order');
}
# Inside Order
public function user(){
return $this->belongsTo('User');
}
// Not sure if this is upsetting anything (also in Order)
public function products(){
return $this->belongsToMany('Product');
}
So I think I have the above right.
But when I do this:
$users = User::with('orders')->find(1);
return $users;
I get Call to a member function addEagerConstraints() on null
.
However, if I do it the other way around, it works great:
$orders = Order::with('User')->get();
return $orders;
What am I doing wrong / what don't I understand?! Or is my problem bigger than I think?
Database:
The problem is you don't have return
for your orders
relationship. It should be:
public function orders(){
return $this->hasMany('Order');
}
You should also use your relationships case sensitive. you showed:
$orders = Order::with('User')->get();
is working, but you should rather use
$orders = Order::with('user')->get();
to avoid extra queries to your database in future
这篇关于Laravel属于使用'with'时返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!