tuscan88
tuscan88

Reputation: 5829

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?

Upvotes: 4

Views: 1648

Answers (2)

tuscan88
tuscan88

Reputation: 5829

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

Upvotes: 2

namelivia
namelivia

Reputation: 2745

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)

Upvotes: 0

Related Questions