0

enter image description hereI am making ecommerce app api using laravel and have 1 table for product data and another table for product images

This query works fine. I want nested query in which each product will have its list of images.I am making android app and need to show multiple product images in carousel slider and need to get nested JSON

$products = DB::table('products')->where ('stock_quantity',  '<>' , 0 )->inRandomOrder()->get();

in products table I have unique 'id' and and same id is used in product_images table to map data.

enter image description here

4
  • Why not using eloquent ? Commented Jul 4, 2020 at 15:57
  • you should add table/model relations between product and product images, eg hasMany and belongsTo then fetch the products with(images). In general outline Commented Jul 4, 2020 at 15:57
  • @NikosM. : He is using query builder not eloquent/model Commented Jul 4, 2020 at 15:58
  • i have read in few articles that eloquent is slow compared query builder. Also, I need to filter product where stock <> 0, which i am not sure in eloquent model. Commented Jul 4, 2020 at 16:06

1 Answer 1

1

i think simple join will do the purpose:

 $products = DB::table('products')->where ('stock_quantity',  '<>' , 0 )->join('product_images',
            'product_images.product_id','products.id')->select('product.*','product_images*')
            ->get();

however, i must say that i don't recommend this kind of storing images, you should store a product_image for each row, not 7 product image for each row ....

Sign up to request clarification or add additional context in comments.

2 Comments

I am able to use joinSub and get all 7 images. what i need is those 7 images to nested . joinSub query $products = DB::table('products')->where ('stock_quantity', '<>' , 0 )->inRandomOrder() // ->joinSub($product_images = DB::table('product_images'), 'product_images', function ($join) {$join->on('products.id', '=', 'product_images.product_id');})->get();
if you want those images to be nested you should rebuild tables schema and build eloquent models

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.