Where 子句未执行

Where clause not enforced

我在laravel之外使用laraveleloquent。 我有一个查询应该只获取有特色的帖子(特色字段 = 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();

我预计此查询会 return 我想要的结果,但 return 也会发布 featured 列不是 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;

在此示例中,我们将始终强制执行特色类型,然后可以 select 任何 3 种也具有特色的类型。

如何用您的语言执行此操作,我不确定。

这对你有用:

$db->table('posts')
    ->where('featured', 1)
    ->whereIn('post_type', ['blog', 'forum', 'page'])
    ->limit(15)
    ->orderBy('created_at', 'desc')
    ->get()->toArray();

您的查询没有按预期工作,因为您使用的 orWhere() 没有闭包,闭包会将 orWhere() 个子句分组。