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_idand department_idwith 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
php eloquent laravel
source share
2 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


, Laravel , laravel, , .

, Product-Brand, , Product by Brand, :

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

Source: https://habr.com/ru/post/1613207/


All Articles