更新(解决方案)
->user
来自 $image
之一的关系内$user->images
,然后 $user
变量已经可用,因为您加载了 ->images
从中! protected $with
Eloquent 属性(property)。这是一种反模式。 原件
我遇到了一个我认为很简单的问题:
User
对象有很多 Image
s Image
属于User
...(逆关系)我的问题是我想同时加载
images()
在 User
模型和 user()
在 Image
模型。为此,我只需设置一个 $with
属性如文档中所述。我的
User
模型:class User extends EloquentModel {
protected $with = ['images'];
public function images()
{
return $this->hasMany(Image::class);
}
}
我的
Image
模型:class Image extends EloquentModel {
protected $with = ['user'];
public function user()
{
return $this->belongsTo(User::class);
}
}
但是在表演的时候:
$user = User::find(203);
这会导致无限循环(php 段错误)。一定有某种我无法找到的循环引用:
[1] 85728 segmentation fault
编辑 2016/02
这是我发现的最简单的“解决方法”:
// User.php
public function setRelation($relation, $value)
{
if ($relation === 'images') {
foreach ($value as $image) {
$image->setUser($this);
}
}
return parent::setRelation($relation, $value);
}
最佳答案
有一个without()
方法:https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Builder.html#method_without
放置without()
在关系的双方都奏效了。
class Property extends EloquentModel {
protected $with = ['images'];
public function images()
{
return $this->hasMany(Image::class)->without('property');
}
}
class Image extends EloquentModel {
protected $with = ['property'];
public function property()
{
return $this->belongsTo(Property::class)->without('images');
}
public function getAlt()
{
return $this->property->title;
}
}
更新:即使使用
without()
轻松避免无限循环问题,通过多年的 Laravel 经验,我意识到设置 $with
是不好的做法。在模型中,因为它会导致始终加载关系。因此导致循环引用/无限循环相反,始终使用
with()
明确指定 急切加载必要的关系,无论多么必要(关系的关系)例如:
$user = User::with('images' => function ($query) {
$query->with('property' => function ($query) {
$query->with('deeperifneeded' => function ($query) {
//...
});
});
]);
注意:可能需要删除 without()
关于laravel-5 - 急切加载 hasMany & BeingsTo(循环引用/无限循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34995187/