I am new to laravel & want to implement eloquent relationship.
Let me explain.
Consider I have 2 tables
products
JavaScript
x
product_id
product_name
brand_id
price
brands
JavaScript
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:
JavaScript
public function brands()
{
return $this->hasOne('AppBrand','product_id');
}
and in Brand model I write:
JavaScript
public function products()
{
return $this->belongsTo('AppProduct','brand_id');
}
Now I want the result:
JavaScript
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??
Advertisement
Answer
Your Product Model relation will be below
JavaScript
public function brand(){
return $this->belongsTo('AppBrand','brand_id');
}
public function product(){
return $this->belongsTo('AppProduct','product_id');
}
Now in controller you can add query as below.
JavaScript
$products = Product::with('brand','product')->get();
echo '<pre>'
print_r($products->toArray());
exit;