简体   繁体   English

Laravel Eloquent 的内部连接

[英]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.也许没有在 Eloquent 模型中使用join

Thanks.谢谢。

Create relationship in your Product model:在您的Product模型中创建关系:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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