根据条件连接 Laravel 中的两个表

Join two tables in Laravel with conditions

我有两个表,我想加入以下条件,只显示产品类型 1 的产品,并且产品应该在 img tbl 中可用,也不应该有 noImg.jpg

products tbl                  img tbl
+-------------------------+   +--------------------------------+
| id   | product_type         | id    | product_id | file
---------------------------   +---------------------------------
| 123  |  1                    | 1    |123         | 1.jpg
| 234  |  2                    | 2    |234         | noImg.jpg
| 345  |  1                    | 3    |345         | 3.jpg

我在 Laravel 中做了以下操作,但似乎查询不正确,因为它没有给我正确的结果。

Product::join('img', function($join) {
                                $join->on('products.id', '=', 'img.product_id')
                                ;
                             })
                                ->where('img.file', '!=', 'noImg.jpg')
                                ->where('products.product_type', 1)
                                ->paginate(100);

试试这个代码

Product::rightJoin('img', function($join) {
    $join->on('products.id', '=', 'img.product_id')
        ->where('img.file', '!=', 'noImg.jpg');
    })
    ->where('products.product_type', '=', 1)
    ->paginate(100);

我相信 img 和 products 是你的 table 名字。

试试这个

Product::rightJoin('img', function($join) {
            $join->on('products.id', '=', 'img.product_id')
            ;
        })
            ->where('img.file', '<>', 'noImg.jpg')
            ->where('products.product_type','=',1)
            ->get();