仅在存在关系时才加载

时间:2017-10-19 10:44:43

标签: laravel laravel-5 eager-loading

我有变形关系,主体可以有多种关系。它们的存在取决于变形模型。我需要检索所有相关的模型(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
    }
}

0 个答案:

没有答案