首页 > 解决方案 > 在 Laravel 中加入两个表

问题描述

我对 Laravel 很陌生,在这里我有一个简单的问题。我需要再将一张表加入以下

   return $products = Product::where('product_type_id', 1)
                            ->where('quantity', '>=', 50)
                             ->where('deleted', 0)
                            ->orderBy('price')
                            ->paginate(100);

我有另一个表名 product_img ,其中存储了所有产品图像。需要获取 product_img 表中产品 id 可用且文件不等于“Noimg.jpg”的所有记录。我尝试了不同的解决方案,但没有奏效。如何在 Laravel 中连接两个表?

我尝试执行以下操作:

$products = Product::leftJoin('product_img', function($join) {
                                $join->on('products.id', '=', 'product_img.product_id')
                                ->where('product_img.file', '!=', 'Noimg.jpg');
                             }) ;
                                ->where('quantity', '>=', 100)
                                ->where('deleted', 0)
                                ->orderBy('price')
                                ->paginate(100);

标签: laravel

解决方案


$products = Product::join('product_img', 'products.id', '=', 'product_img.product_id')
                                ->where('product_img.file', '!=', 'Noimg.jpg')
                                ->where('quantity', '>=', 100)
                                ->where('deleted', 0)
                                ->orderBy('price')
                                ->paginate(100);

推荐阅读