laravel 使用“with”时,LaravelbelongsTo 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26778082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel belongsTo returning null when using 'with'
提问by Djave
I'm just getting started with Laravel so please forgive any noobness.
我刚刚开始使用 Laravel,所以请原谅任何菜鸟。
I have a User
and Order
model, a user has many orders:
我有一个User
和Order
模型,一个用户有很多订单:
# 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
.
我明白了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:
数据库:
回答by Marcin Nabia?ek
The problem is you don't have return
for your orders
relationship. It should be:
问题是你没有return
你的orders
关系。它应该是:
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
避免将来对您的数据库进行额外查询
回答by glmdev
For anyone else that runs across this, I was having the same issue, but my problem was that I had the foreign/local keys swapped. Example:
对于遇到此问题的任何其他人,我遇到了同样的问题,但我的问题是我交换了外/本地密钥。例子:
// This is correct for hasX relationships
public function user() {
return $this->hasOne('App\Models\User', 'user_id', 'local_key_user_id');
}
// This is correct for belongsTo relationships
public function user() {
return $this->belongsTo('App\Models\User', 'local_key_user_id', 'user_id');
}
Notice that for hasX relationships, the foreign key is the second parameter, and the local key is the third. However, for belongsTo relationships, these two are swapped.
请注意,对于 hasX 关系,外键是第二个参数,本地键是第三个参数。然而,对于belongsTo 关系,这两个被交换。