My scenario is I have 3 different tables
tblProducts -- List of Products --
id (Primary Key)
product_title
deleted (Default value is 0 if not deleted, if deleted value is 1. Same below)
tblClass -- List of Classes --
id (Primary Key)
class_title
deleted
tblClassPerProduct -- Assigned Classes per specific product--
id (Primary Key)
product_id (Key : tblProducts)
class_id (Key : tblClass)
deleted
So what I'm trying to do is to get the nested json query of this relationship
Expected output using query builder
[{
"id" : 1,
"product_title" : "Product1",
"deleted " : 0,
"classes_per_product" :
{
"id": 1,
"product_id" : 1,
"class_id": 1,
"class_title":"class 1",
"deleted_class_per_product" : 0,
"deleted_class" : 0
},
{
"id": 2,
"product_id" : 1,
"class_id": 2,
"class_title":"class 2",
"deleted_class_per_product" : 0,
"deleted_class" : 0
},
{
"id": 3,
"product_id" : 1,
"class_id": 3,
"class_title":"class 3",
"deleted_class_per_product" : 0,
"deleted_class" : 0
},
.....So on
I just want to get all classes assigned on each products
Currently I have this code
$data = DB::table('tblProducts')
->select( 'tblProducts.id', 'tblProducts.product_title', 'tblProducts.deleted' )
->where('tblProducts.deleted',0)
->get();
return $data;
Trying to do the nested json response.
One option is, doing it in eloquent model relationship. But my problem is there is existing query that I need to follow. So I simplify the things that I need in this question.
->join()just like in a regular query. Although you will not receive nested data like your expected result, since the raw query builder will only return flat row objects (basically raw SQL output).