[英]Eloquent ORM returns null using with() eager load
When using Eloquent's with() the eager loaded data sometimes becomes null
. 当使用Eloquent的with()时,渴望加载的数据有时会变为
null
。 In my case, I have three tables, Users
, Blogposts
and Categories
. 就我而言,我有三个表,
Users
, Blogposts
和Categories
。 The blogposts table has two foreign keys, called author
and category
. Blogposts表具有两个外键,称为
author
和category
。 The query performed is given by 执行的查询由
return Blogpost::with(['author', 'category'])->get();
The response is, well, odd. 答案很奇怪。 Note that
author
becomes null
from id: 3
and category
from id: 4
. 请注意,
author
从id: 3
变为null
,从id: 4
变为category
。
In reality both the ids 1
, 3
have the same author (superuser) as do the ids 2
, 4
(steve). 在现实中两者的ID
1
, 3
具有相同的作者(超级用户)作为做的ID 2
, 4
(史蒂夫)。 Also id 1
, 4
have the same category (web dev). 也ID
1
, 4
具有相同的类别(web开发)。
It seems as if a/an category/author is already retrived and bounded to a blogpost the past categories/authors becomes null. 似乎某个类别/作者已被检索并绑定到博客帖子,过去的类别/作者似乎为空。
[
{
id: 4,
author: null,
image_name: "banner1.png",
category: null,
intro: "Hello World!",
},
{
id: 3,
author: null,
image_name: "banner1.png",
category: {
id: 3,
name: "big data",
},
intro: "Hello World!",
},
{
id: 2,
author: {
id: 2,
email: "foo@foo.foo",
fullname: "foo foo",
is_admin: false,
},
image_name: "banner1.png",
category: {
id: 2,
name: "science",
},
intro: "Hello World!",
},
{
id: 1,
author: {
id: 1,
email: "superuser@superuser.com",
fullname: "superuser superuser",
is_admin: true,
},
image_name: "banner1.png",
category: {
id: 1,
name: "web dev",
},
intro: "Hello World!",
}
]
Finally here are the relations defined in the models 最后是模型中定义的关系
// User model
public function blogposts() {
return $this->hasMany('App\Blogpost', 'id');
}
// Blogpost model
public function author() {
return $this->belongsTo('App\User', 'id');
}
public function category() {
return $this->belongsTo('App\Category', 'id');
}
// Category model
public function blogposts() {
return $this->hasMany('App\Blogpost', 'id');
}
Is there any explanation to this? 有什么解释吗?
It appears the fault was in the model definitions, here are the corrected models. 似乎是模型定义中的错误,这是更正后的模型。
// User model
public function blogposts() {
return $this->hasMany('App\Blogpost', 'id', 'author');
}
// Blogpost model
public function author() {
return $this->belongsTo('App\User', 'author', 'id');
}
public function category() {
return $this->belongsTo('App\Category', 'category', 'id');
}
// Category model
public function blogposts() {
return $this->hasMany('App\Blogpost', 'id', 'category');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.