如何在 laravel 中的一个查询语句中加入 Eloquent 和查询生成器

How to Join Eloquent and Query Builder in one query statement in laravel

我有 2 个查询需要加入,第一个是 eloquent,第二个是查询生成器,

第一次查询

$products = Product::all();

第二次查询

$inventory = DB::table('product_warehouse')
->where('product_id', $product_id)
->where('warehouse_id', $warehouse_id)
->first();

如何将这 2 个查询合并为 elouquent 方式?

从您对查询生成器的使用来看,您似乎有一个中间 table 来存储哪个产品到哪个仓库,但如果它是一对多关系,您不应该有那个 table,而不是在你的产品 table 中,你应该有一个 warehouse_id,它将引用 warehouses table 上的 id,正如你所说的关系是一个很多,不是很多。

所以在您的 Warehouse 模型中您可以添加:

public function products()
{
    return $this->hasMany(Product::class);
}

在您的 Product 模型中:

public function warehouse()
{
    return $this->belongsTo(Warehouse::class);
}

根据您的 table 名称,您可能需要在仓库模型中设置 $table 以匹配:

protected $table = 'product_warehouse';

那么你有很多种获取方式,其中一种是:

Warehouse::find($warehouse_id)->products;

// or 

Warehouse::with('products')->where('id', $warehouse_id)->get();

// to get the warehouse to which the product belongs to
Product::find($product_id)->warehouse;