我有一个变形关系,其中主体可以有多个关系。它们的存在取决于变形模型。我需要检索所有相关模型(whereHas()
不能解决问题),如果它们存在于特定模型上,我希望加载它们的关系(with()
不起作用,因为关系并不总是存在)。
我可以使用其他东西(内置)来流畅地解决这种情况,或者黑客是唯一的解决方法?
<?php
...
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany('AppComment', '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('AppComment', '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
}
}
在查询范围中查看。
有了它,您可以创建一个范围来加载关系(如果存在),例如:
User::withRelationIfExists('cars')->where(...)
例如:(代码未测试)
public function scopeWithRelationIfExists($query, $relation)
{
if (! method_exists(get_class(), $relation)) {
return;
}
return $query->with($relation);
}