Larvel 5.1 eloquent belongs to joining relationships across multiple columns
I am connecting to a remote database that was poorly developed, but I just can’t fix it. I have read-only access to get the data I need. It has the following structure:
Products
- id
- style_id
- department_id
Brands
- id
- Name
- style_id
- department_id
Since you can see, and not a product that has only a field brand_id
, it has style_id
and department_id
with which you must join in order to find out which brand is the product.
So, how would I establish my relationship with my product model in order to achieve this?
+4
geoffs3310
source
share2 answers
, .
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.*']);
}
+2
geoffs3310
, Laravel , laravel, , .
, Product-Brand, , Product by Brand, :
Product::where('style_id',$brand->style_id)->where('department_id',$brand->department_id)
+1
namelivia