Home > Mobile >  Laravel Join : Selecting all matching rows
Laravel Join : Selecting all matching rows

Time:09-27

i am trying to fetch product attributes by product id as below

$data['product']=  Product::select('products.*','product_attributes.id as product_attribute_id','product_attributes.name as
                  'product_attribute_name',
                  'product_attributes.value as product_attribute_value')
                   ->leftjoin('product_attributes','product_attributes.product_id','=','products.id')
                  ->where('products.id','=',$request['id'])
                  ->get();

Below is my structure for attributes table

enter image description here

Now what happens is when i try to fetch product attributes it only returns my one of the attributes (first record in attributes table)

Can someone please help me how can i fetch all the attributes for any given product_id

EDIT ::

just noticed when i dump data it returns me 3 records (indexes) , each index has one attribute value and product data( product data is repeating ) and i have only three attribute entries so it gives me 3 indexes ,

CodePudding user response:

Please try to use relations.

define attributes relation in the Product Model.

public function attributes() 
{
    return $this->hasMany(Attribute::class)
}

So the query would be easy now. As

Product::with('attributes')->findOrFail($productId);

Important Docs,

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

https://laravel.com/docs/8.x/eloquent-relationships

CodePudding user response:

Try this I think it will work for your case.

    $data['product']=  Product::find($request['id']);

    $data['product_attributes'] = ProductAttributes::where('product_id','=',$request['id'])
                      ->get();
  • Related