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('AppBrand','product_id'); }
and in Brand model I write:
public function products() { return $this->belongsTo('AppProduct','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??
Advertisement
Answer
Your Product Model relation will be below
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.
$products = Product::with('brand','product')->get(); echo '<pre>' print_r($products->toArray()); exit;