请教一下多态关联的这种查询怎么查?
表结构如下
//帖子表
posts
id - integer
name - string
//用户表
users
id - integer
name - string
//标签表
tags
id - integer
name - string
//标签关联表
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
现在有三张表,用户表(users),帖子表(users),标签表(tags),用户和帖子都是多态关联了标签表。
//UserModel
public function tags()
{
return $this->morphToMany(TagModel::class, 'taggable', 'taggables')->withTimestamps();
}
//PostModel
public function tags()
{
return $this->morphToMany(TagModel::class, 'taggable', 'taggables')->withTimestamps();
}
需求是:查询出帖子的标签,和用户的标签,有重合的帖子,且标签重合数量越多排序在越前面。
各位有什么思路吗?
可以试试使用
withCount()
: