Laravel 5.3 多对多多态 - 如何获取所有相关行,而不管它们 table 按数据透视列排序?

Laravel 5.3 Polymorphic many to many - how to get all the related rows regardless of their table sorted by pivot column?

我有一个模型 Page 和许多称为 SomethingSection 的模型 - 它们通过多态 m-m 关系连接,并且枢轴有一个额外的列 'position'。

我需要在 Page 模型上写一个关系(或者可能是访问器?),它将 return 所有连接部分的集合,无论它们的模型如何(阅读:table)。

我的模特:

class Page extends Model {

    public function introSections()
    {
        return $this->morphedByMany(IntroSection::class, 'pagable');
    }

    public function anotherSections()
    {
        return $this->morphedByMany(AnotherSection::class, 'pagable');
    }
}

class IntroSection extends Model {

    public function pages()
    {
        return $this->morphToMany(Page::class, 'pagable');
    }
}

class AnotherSection extends Model {

    public function pages()
    {
        return $this->morphToMany(Page::class, 'pagable');
    }
}

数据透视列如下所示:

pagables
    -page_id
    -pagable_id
    -pagable_type
    -position

我正在寻找一种在页面模型上调用 method/attribute 并将所有连接的部分放在一个集合中并进行排序的方法。解决这个问题的好方法是什么?

我知道连接的部分没有相同的界面,但在我的情况下这根本不是问题(就我将如何处理数据而言)。

我也明白关系执行一个单独的查询(对于每个关系),所以用 1 个查询获取所有这些是不可能的(不同的接口在这里也是一个问题)。出于同样的原因,排序将需要在集合级别而不是在查询中完成。

我怎样才能使它尽可能易于维护,并且最好尽可能减少性能损失。

提前致谢。

您可以在您的关系之后使用 withPivot() 方法来获取具有如下关系的数据透视列:

class Page extends Model {

    public function introSections()
    {
        return $this->morphedByMany(\HIT\Models\Sections\IntroSection::class, 'pagable')
                                ->withPivot(['position']);
    }

    public function anotherSections()
    {
        return $this->morphedByMany(AnotherSection::class, 'pagable');
    }
}

class IntroSection extends Model {

    public function pages()
    {
        return $this->morphToMany(Page::class, 'pagable')
                                ->withPivot(['position']);
    }
}

并且您可以使用集合的 sortBy 来使用 sortBy() 方法对集合进行排序,如下所示:

$sorted_collection = IntroSection::pages->sortBy('pagables.position');

更新:

您可以使用集合的 combine() 方法来获取所有这样的关系,将此方法添加到您的 Page Class:

public function getAllSections()
{
    return $this->introSections->combine($this->anotherSections-toArray())
                ->sortBy('pagables.position'):
}

希望对您有所帮助!