简体   繁体   中英

Laravel 5.1 eloquent belongsTo relationship joining on multiple columns

I am connecting to a remote database that has been designed poorly but I can't amend it in any way I only have read access to the get the data I need. It has the following structure:

Products
    - id
    - style_id
    - department_id

Brands
    - id
    - Name
    - style_id
    - department_id

So as you can see rather than a product just having a brand_id field it has a style_id and department_id that you have to join on in order to find out what brand a product is.

So how would I set up my belongsTo relationship in my Product model in order to achieve this?

I made a scope in the end to do this for me.

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.*']);
}

As far as I know Laravel does not support composite keys, there is an issue opened on the laravel repo where the devs have answered that they don't have intentions of implementing that.

I think you can only query Product-Brand queries like for example Products by Brand combining wheres like this:

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

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