【发布时间】:2017-10-19 10:44:43
【问题描述】:
我有一个变形关系,主题可能有多个关系。它们的存在取决于变形模型。我需要检索所有相关模型(whereHas() 不能解决问题),如果它们存在于特定模型上,我希望加载它们的关系(with() 不起作用,因为关系并不总是存在) .
我可以使用其他任何东西(内置)来流畅地解决这种情况,或者黑客是解决它的唯一方法吗?
<?php
...
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
/**
* This relationship is available for Post model only
*/
public function relationA()
{
// return $this->hasMany(...);
}
}
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
/**
* This relationship is available for Video model only
*/
public function relationB()
{
// return $this->hasMany(...);
}
}
class Comment extends Model
{
/**
* Get all of the owning commentable models.
*/
public function commentable()
{
return $this->morphTo();
}
public static function feed()
{
self::with('commentable')
->withIfExists(['commentable.relationA', 'commentable.relationB'])
// ...
->get();
}
public function scopeWithIfExists($query, $relation)
{
// There is no way to implement such a scope
// in order to reduce umber of queries by eager loading relations
// as we don't know of what type the subject is
// without looking it up in database
}
}
【问题讨论】:
标签: laravel laravel-5 eager-loading