【问题标题】:Laravel Query Builder get data from other table under certain conditionLaravel Query Builder 在特定条件下从其他表中获取数据
【发布时间】:2020-11-14 10:13:45
【问题描述】:

您好,我正在尝试从另一张桌子上获取特定产品。 这是我的产品表

我还有一个名为 banned_products 的表:

我很难使用 Laravel 查询生成器获取正确的数据。 这是我目前所拥有的:

    $banned_products = DB::table('banned_products')
        ->select('product_id')
        ->where('reason', '=', 'unknown')
        ->groupBy('product_id');


    return DB::table('products')
        ->leftJoinSub($banned_products, 'banned_products', function ($join) {
            $join->on('products.id', '=', 'banned_products.product_id');
        })
        ->select(
            'products.id as product_id',
            'products.identifier')
        ->whereNull('products.deleted_at')->get();

此查询返回所有产品,但不返回我想要的原因未知的已删除产品。

怎么做?

感谢您的阅读。

【问题讨论】:

    标签: mysql laravel laravel-query-builder


    【解决方案1】:

    如果以下方法可行,你可以试试吗?

    DB::table('products')
    ->rightJoin('banned_products', 'banned_products.product_id', 'products.id')
    ->where(function ($query) {
        $query->where('banned_products.reason', 'unknown')
        ->orWhereNull('banned_products.id');
    })
    ->get(['products.id as product_id', 'products.identifier']);
    
    /*
    SQL Query:
    
    select
       "products"."id" as "product_id",
       "products"."identifier"
    from "products"
    right join "banned_products" on "banned_products"."product_id" = "products"."id"
    where (
       "banned_products"."reason" = "unknown"
       or "banned_products"."id" is null
    )
    
    */
    

    【讨论】:

    • 您好 IGP 感谢您的回复,您的查询没有返回我所有的产品 + 被禁止的产品,原因 = 未知。只有在产品原因不明的情况下,它才会将被禁止的产品与其他产品一起退回给我。
    • 我看错了你的问题。我以为你想要所有未被禁止的产品,原因不明。它应该是相同的查询,但不要使用 whereNotExists/whereDoesntHave 使用 whereExists/whereHas
    • 感谢您的快速响应,现在它返回空值。在数据库查询生成器上,它只返回我被禁止的产品,原因未知,如何获取其他产品?
    • 哦,对了。如果您只想要删除的产品,它应该是 whereNotNull 而不是 whereNull
    • 这样它会将已删除的产品退回给我,而没有其他产品。
    猜你喜欢
    • 2016-05-21
    • 2022-12-07
    • 2015-10-14
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多