0

I have searched through whole internet and couldn't find any reliable solution for this problem

so i have tables as follow:

  1. products
  • id
  • name
  • description
  1. subcategories
  • id(pk)
  • subcategory_name
  • is_active
  1. product_details
  • id (pk)
  • product_id(fk)
  • sku
  • price
  • subcategory_id(fk)
  • is_active
  1. product_attributes
  • id (pk)
  • product_detail_id (fk)
  • size_id (fk)
  • color_id (fk)
  • material_id(fk)
  • brand_id (fk)
  • rating
  1. sub_images
  • id(pk)
  • product_attribute_id(fk)
  • sub_image

Now want result of these as multidimensional array like this

i'm just novice at eloquent models so only option left is writing queries with query builder and converting them into multidimensional array. But i dont know how! Please help me

1 Answer 1

1

Make use of the laravel relationships :

$response = Products::with(['productDetails',
                'productDetails.productAttributes',
                'productDetails.productAttributes.subImage'])->get();

If you want the response as array :

$response = $response->toArray();

Products Model

In the products model add the hasMany relationship, in the screenshot the product details is mentioned as an array, if you have multiple entries for the product details table use the hasMany or else use hasOne relationship

/**
 * If you have multiple details in product details table
 */
public function productDetails(){
    return $this->hasMany(ProductsModel::class,'product_id','id');
}

has one relationship

/**
 * If you have single entry for product details table
 */
public function productDetails(){
    return $this->hasOne(ProductsModel::class,'product_id','id');
}

ProductDetails Model

Inside the product details model add the relationship to the product attributes table

public function productAttributes(){
    return $this->hasMany(ProductAtrributesModel::class,'product_detail_id','id');
}

ProductAtrributesModel Model

Inside the product attributes model add the relationship with the images to the product attributes table

public function subImages(){
    return $this->hasMany(ProductSubImagesModel::class,'product_attribute_id','id');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Dear Sir Thank you for your answer. I was able to get expected result with above mentioned eloquent query before, but i'm only getting ids of relational table and not value,like i want name of sub category which doesnt belong to product hierarchy and mentioned only in product_details table as foreign key. how can i get the that value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.