Order by count in many to many polymorphic relation in Laravel
让我们以doc为例:https://laravel.com/docs/5.7/eloquent-relationships#many-to-many-polymorphic-relations很容易获得所有
但是如何获取所有
如果我执行
因此,在进行更多搜索之后,我发现仅凭一个查询就无法执行此操作,原因是在
1 2 3 4 5 6 7 8 9 10 11 12 13 | public function scopeWithTaggablesCount($query) { if (is_null($query->getQuery()->columns)) { $query->select($query->getQuery()->from . '.*'); } $query->selectSub(function ($query) { $query->selectRaw('count(*)') ->from('taggables') ->whereColumn('taggables.tag_id', 'tags.id'); }, 'taggables_count'); return $query; } |
要使用它:
1 | $tags = Tag::withTaggablesCount()->orderBy('name', 'ASC')->get(); |
因此,现在每个标签都有一个
我建议您简单地执行您已经进行的通话,即
1 2 3 4 5 6 7 8 9 10 11 | // Tag.php class Tag { ... // Create an attribute that can be called using 'taggables_count' public function getTaggablesCountAttribute() { return $this->videos_count + $this->posts_count; } ... } |
,然后在循环中(或使用集合中的项目):
1 2 3 | @foreach($tags as $tag) {{ $tag->taggables_count }} @endforeach |
此设置要求您使用
如果您真的担心速度,则必须手动创建查询并在其中进行添加。