【发布时间】:2019-10-22 10:15:31
【问题描述】:
我有三个表,一个articles表,一个tags表,还有一个叫做article_tags的中间数据透视表,它只包含一个article_id和tag_id,形成了多对多的关系。
我想写一个函数来接收一篇文章,并返回一个集合或查询所有与接收到的文章共享至少一个标签的文章,在尝试了一堆不同的解决方案之后,我有这个:
public function scopeRelated($query, Article $article)
{
return $query->whereHas('tags', function ($query) use ($article) {
// I've tried a bunch of different lines, like just $article->tags
$query->whereIn('tags', $article->tags->pluck('id'));
});
}
这会返回一个错误:
使用消息“SQLSTATE[42S22] 照亮/数据库/查询异常: 未找到列:1054 'where 子句'中的未知列 'tags'(SQL: select * from
articleswhere exists (select * fromtagsinner joinarticle_tagontags.id=article_tag.tag_id在哪里articles.id=article_tag.article_id和tags在 (1, 6, 4)))'
显然,Eloquent 正在尝试将标签与 Articles 表中不存在的“标签”列进行匹配。 问我想要什么的正确方式是什么?
【问题讨论】:
标签: php laravel laravel-5 eloquent