shino47
shino47

Reputation: 213

Inner join in Laravel Eloquent

I have a working query, but would like to know if there is a more elegant way to do it. I have a Product table and a Manufacturer table.

The relationships are as follows:

Manufacturer > hasMany > Product
Product > belongsTo > Manufacturer

My query is:

$products = \App\Product::join('manufacturers', 
        'products.manufacturer_id', '=', 'manufacturers.id')
    ->where('manufacturers.name', 'like', $needle)
    ->orWhere('products.name', 'like', $needle);

Is this right? Is there a better way? Maybe without using join in a Eloquent model.

Thanks.

Upvotes: 0

Views: 2813

Answers (1)

Andrii Lutskevych
Andrii Lutskevych

Reputation: 1389

Create relationship in your Product model:

public function manufacturer()
{
    return $this->belongsTo(Manufacturer::class, 'foreign_key');
}

and then you can use

$products = \App\Product::whereHas('manufacturer', function ($query) use ($needle) {
    $query->where('name', 'like', $needle);
})->orWhere('name', 'like', $needle);

Upvotes: 2

Related Questions