UPDATE (SOLUTION)
- If you need
->user
relationship from one of the $image
inside $user->images
, then $user
variable is already available cause you loaded the ->images
from it!
- Don't use
protected $with
Eloquent property. It's an anti-pattern.
- Instead explicitly eager load relationships on-demand from where/when it's needed (Note: it should not prevent you to keep things DRY!)
- If you really need/want to, see @nicksonyap answer. It does the trick (I believe – not tested).
ORIGINAL
I'm running into what I believe is a simple problem:
- I have a
User
object that has many Image
s
Image
belongs to User
... (inverse relation)
My problem is that I want to eager load both the images()
on the User
model and the user()
on the Image
model. To do so, I just setup a $with
property as explained in the docs.
My User
model:
class User extends EloquentModel {
protected $with = ['images'];
public function images()
{
return $this->hasMany(Image::class);
}
}
My Image
model:
class Image extends EloquentModel {
protected $with = ['user'];
public function user()
{
return $this->belongsTo(User::class);
}
}
But when performing:
$user = User::find(203);
This results in an infinite loop (php segmentation fault). There must be some kind of circular reference that I am not able to locate:
[1] 85728 segmentation fault
EDIT 2016/02
This is the simplest "Workaround" I found:
// User.php
public function setRelation($relation, $value)
{
if ($relation === 'images') {
foreach ($value as $image) {
$image->setUser($this);
}
}
return parent::setRelation($relation, $value);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…