Reputation: 5829
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
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
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