我使用laravel雄辩的外面laravel。 我有一个查询应该只获得特色帖子(特色字段= 1)和3种类型(博客,论坛和页面)中的任何一种。
$latestFeaturedPosts = $db->table( 'posts' )
->where( 'featured', '=', 1 )
->orWhere( 'post_type', '=', 'blog' )
->orWhere( 'post_type', '=', 'forum' )
->orWhere( 'post_type', '=', 'page' )
->limit( 15 )
->orderBy( 'created_at', 'desc' )
->get()->toArray();
我希望此查询返回我想要的内容,但它确实会返回featured
列不为1的帖子。
为什么?我应该如何修改此语法来强制执行此操作?
答案 0 :(得分:1)
我现在不用这种语言,但会给你一个起点来研究。
您的查询将扩展为:
SELECT * FROM posts where featured = 1 OR post_type = 'blog' OR post_type = 'forum' OR post_type = 'page' LIMIT 15 ORDER BY created_at DESC;
在此查询中,将返回与4个条件中的任何一个匹配的任何行。
为了获得您期望的结果,您的查询需要评估为:
SELECT * FROM posts where featured = 1 AND ( post_type = 'blog' OR post_type = 'forum' OR post_type = 'page' ) LIMIT 15 ORDER BY created_at DESC;
在这个例子中,我们将始终强制使用特色类型,然后可以选择任何3种类型的特征。
如何用您的语言进行此操作,我不确定。
答案 1 :(得分:0)
这对你有用:
$db->table('posts')
->where('featured', 1)
->whereIn('post_type', ['blog', 'forum', 'page'])
->limit(15)
->orderBy('created_at', 'desc')
->get()->toArray();
您的查询没有按预期工作,因为您使用orWhere()
而没有可以将orWhere()
条款分组的闭包。