Laravel 5.1的eloquent belongsTo关系连接在多个列上


Laravel 5.1 eloquent belongsTo relationship joining on multiple columns

我正在连接到一个设计得很差的远程数据库,但我不能以任何方式修改它,我只有读取权限才能获得我需要的数据。它的结构如下:

Products
    - id
    - style_id
    - department_id
Brands
    - id
    - Name
    - style_id
    - department_id

因此,正如您所看到的,而不是一个产品只有一个brand_id字段,它有一个style_iddepartment_id,你必须加入,以找出一个产品是什么品牌。

那么如何在Product模型中设置belongsTo关系来实现这一点呢?

最后我做了一个作用域来为我做这些。

public function scopeWithBrand($query)
{
    $query->join('Brands', function($q) {
        $q->on('Products.department_id', '=', 'Brands.department_id')
          ->on('Products.style_id', '=', 'Brand.style_id');
    })->addSelect(['Brands.id AS brand_id', 'Products.*']);
}

据我所知Laravel不支持复合键,有在laravel版本中出现了一个问题,开发者回答说他们没有实现这个的意图。

我认为你只能查询产品-品牌的查询,例如,产品按品牌组合,像这样:

Product::where('style_id',$brand->style_id)->where('department_id',$brand->department_id)