简体   繁体   中英

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

I have 2 queries that needed to join 1st is eloquent and 2nd is query builder,

1st Query

$products = Product::all();

2nd Query

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

How to merge this 2 queries into elouquent way ?

From your usage of the query builder it seems like you have an intermediate table to store which product to which warehouse exist, but if it is a one to many relationship you should not have that table, instead in your products table you should have a warehouse_id which will reference the id on the warehouses table, as you said the relationship is one to many, not many to many.

So in your Warehouse model you can add:

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

And in your Product model:

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

Based on your table name, you might need to set the $table in your warehouse model to match that:

protected $table = 'product_warehouse';

Then you have many ways to fetch it, one of which is :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM