【问题标题】:How to bind parameter in sub query in Laravel?如何在 Laravel 的子查询中绑定参数?
【发布时间】:2020-10-28 10:57:37
【问题描述】:

我在 join 中有一个子查询,我在其中使用 where 子句,但它给了我错误

找不到列:1054 'where 子句'中的未知列'products.id'

以下是我的查询:

Product::leftJoin(
                'categories',
                'products.category_id',
                '=',
                'categories.id'
            )
            ->join('vendor_products', function ($join) {
                $join->on(
                    'products.id',
                    '=',
                    'vendor_products.product_id'
                )
            })
            ->leftJoin('brand_products', function ($join) {
                    $join->on(
                        'products.id',
                        '=',
                        'brand_products.product_id'
                    )->on(
                        'brand_products.brand_id',
                        '=',
                        DB::raw('(
                            SELECT brand_id FROM 
                            (SELECT brand_id, COUNT(brand_id) productCount 
                            FROM brand_products
                            where brand_products.product_id = products.id
                            inner join brand on brand_products.brand_id = brand.id
                            GROUP BY brand_id order by productCount desc, DATE(brand.created_at) asc limit 1) as results)')
                    );
            })
            ->get();

这是导致错误where brand_products.product_id = products.id的行。

任何帮助都将不胜感激。

【问题讨论】:

    标签: php laravel laravel-query-builder


    【解决方案1】:

    在您的原始查询中添加产品表以及 FROM 像这样

    DB::raw('(
            SELECT brand_id FROM 
            (SELECT brand_id, COUNT(brand_id) productCount 
            FROM brand_products,products,brand
            where brand_products.product_id = products.id
            inner join brand on brand_products.brand_id = brand.id
            GROUP BY brand_id order by productCount desc, DATE(brand.created_at) asc limit 1) as results)')
    

    我希望它会工作

    【讨论】:

    • 语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以了解在 'inner join brand on brand_products.brand_id = brand.id 附近使用的正确语法
    • @HarrisKhan 将内部连接线放在 where 子句上方
    • 违反完整性约束:1052 字段列表中的列 'brand_id' 不明确,现在收到该错误
    • 我也尝试使用brand_products.brand_id,但没有成功
    • @HarrisKhan 在 FROM 部分中添加品牌以及产品和品牌产品
    猜你喜欢
    • 2014-09-08
    • 2018-08-11
    • 1970-01-01
    • 2016-06-27
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2013-07-18
    相关资源
    最近更新 更多