【问题标题】:How to Join Eloquent and Query Builder in one query statement in laravel如何在 laravel 的一个查询语句中加入 Eloquent 和 Query Builder
【发布时间】:2019-05-30 06:02:35
【问题描述】:

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

第一次查询

$products = Product::all();

第二次查询

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

如何将这两个查询合并成雄辩的方式?

【问题讨论】:

  • 你的关系是多对多(一个产品可以存在多个仓库),还是一对多(一个仓库多个产品)?
  • 每个仓库一个产品,所以一个仓库有很多产品

标签: php laravel eloquent laravel-query-builder


【解决方案1】:

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

因此,您可以在 Warehouse 模型中添加:

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

在您的Product 模型中:

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

根据您的表名,您可能需要在仓库模型中设置 $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;

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2020-02-20
    • 2021-08-19
    • 1970-01-01
    • 2016-07-25
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多