[英]Eager loading on polymorphic relations
class Admin {
public function user()
{
return $this->morphOne('App\Models\User', 'humanable');
}
public function master()
{
return $this->hasOne('App\Models\Master');
}
}
class Master {
public function admin()
{
return $this->hasOne('App\Models\Admin');
}
}
class User {
public function humanable()
{
return $this->morphTo();
}
public function images()
{
return $this->hasOne('\App\Models\Image');
}
}
class Image {
public function user()
{
return $this->belongsTo('\App\Models\User');
}
}
Now if I dump this: 现在,如果我转储此:
return \App\Models\Admin::where('id',1)->with(array('user.images','master'))->first();
I get the perfect result one master, one user and one image record. 我得到了一个完美的结果,一个主控,一个用户和一个图像记录。
But if I do this 但是如果我这样做
return $user = \App\Models\User::where('id',1)->with(array('humanable','humanable.master'))->first();
I only get one Admin record, the query get * from masters doesn't even run. 我只得到一个管理员记录,从主目录获取*的查询甚至没有运行。
Any idea what I'm doing wrong, I'm sure this is possible. 知道我在做什么错了,我相信这是可能的。
If I remember correctly Laravel has lots of pitfall. 如果我没记错的话,Laravel有很多陷阱。 You can try to use the
protected $with
var in Admin model instead of query builder with function. 您可以尝试在Admin模型中使用
protected $with
var,而不要使用带有功能的查询生成器。
class Admin {
protected $with = ['master'];
public function user() {
return $this->morphOne('App\Models\User', 'humanable');
}
public function master() {
return $this->hasOne('App\Models\Master');
}
}
In query builder, only need to include humanable
. 在查询构建器中,只需要包含
humanable
。 Now you should see master inside the humanable object. 现在,您应该在可操作对象内部看到master。
return $user = \App\Models\User::where('id',1)->with('humanable')->first();
Hope this help. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.