2
votes

I am new to laravel & want to implement eloquent relationship.

Let me explain.

Consider I have 2 tables

products

 product_id
 product_name
 brand_id
 price

brands

 id
 brand_name

Each product will have one brand Id.But in Brands table, there is no product id. One brand_id can be in multiple product rows, and one product has one brand_id only. I want to select some col from products table plus brand_name with respect to brand_id of products table using Model.SO in Product model I wrote:

public function brands()
    {   
        
        return $this->hasOne('App\Brand','product_id');
    }

and in Brand model I write:

public function products()
    {
        return $this->belongsTo('App\Product','brand_id');
    } 

Now I want the result:

product_name
price
brand_name

How can I fetch those data in controller using eloquent relation? Also, the way I wrote Model relationship, Is it ok??

2

2 Answers

2
votes

Your Product Model relation will be below

public function brand(){   
    return $this->belongsTo('App\Brand','brand_id');
}
public function product(){   
    return $this->belongsTo('App\Product','product_id');
}

Now in controller you can add query as below.

$products = Product::with('brand','product')->get();
echo '<pre>'
print_r($products->toArray());
exit;
2
votes

It looks to me like you want a one-to-many relationship, so one brand can have many products and many products belong to one brand.

Product model:

public function brand()
{
    return $this->belongsTo('App\Brand');
}

Brand model:

public function products()
{
    return $this->hasMany('App\Product');
}

Then you would be able to get the brand information like this:

The full brand model:

Product::first()->brand

The brand name:

Product::first()->brand->brand_name

From the docs:

A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments.

P.S.:

Your table column names do not make much sense to me, why do you have product_id on products but then on brands it is just called id? Why do you have product_name but then just price? why is it not just name or product_price, so your at least consistent?