categories<-subgaterories->plan how to get categories id wise fetch data laravel - laravel

**i want **
$PlanDetails= PalnCategory::select('id','title')->with('Categorys'[subplandetails])->get();
my api response
[
{
"id": 1,
"title": "category 1",
"categorys": [
{
"id": 5,
"subcategor_name": "regular"
},
{
"id": 6,
"subcategor_name": "primum"
}
]
},
{
"id": 2,
"title": "category 2",
"categorys": [
{
"id": 7,
"subcategor_name": "cat2 reg"
}
]
}
]
i want to show
[
{
"id":1,
"title":"category 1",
"categorys":[
{
"id":5,
"subcategor_name":"regular",
"plans":[
{
"id":1,
"name":"plan1"
},
{
"id":2,
"name":"plan2"
}
]
},
{
"id":6,
"subcategor_name":"primum",
"plans":[
{
"id":3,
"name":"plan3"
},
{
"id":4,
"name":"plan4"
}
]
}
]
},
{
"id":2,
"title":"category 2",
"categorys":[
{
"id":7,
"subcategor_name":"cat2 reg",
"plans":[
{
"id":3,
"name":"plan3"
},
{
"id":4,
"name":"plan4"
}
]
}
]
}
]
my model
public function Categorys()
{
return $this->belongsToMany(PlanSucategory::class)->select('id','subcategor_name');
}
public function PlanDetails()
{
return $this->belongsToMany(PlanDetail::class);
}
my controller
$PlanDetail= PalnCategory::select('id','title')->with('Categorys','PlanDetails')->get();
return response()->json($PlanDetail);
here subcategories id same anthor to table categories<-subcategories->plandetails but i want to fetch data categories->subcategories->plandetails
here subcategories id same anthor to table categories<-subcategories->plandetails but i want to fetch data categories->subcategories->plandetailshere subcategories id same anthor to table categories<-subcategories->plandetails but i want to fetch data categories->subcategories->plandetails

I'm not going to modify your query, but instead use a collection, which will transform the data after the get() method.
$PlanDetail = PalnCategory::select('id','title')
->with('Categorys','PlanDetails')
->get()
->groupBy('categorys.0.id')
->values()
->map(function($item){
$sub = collect($item)->map(function($item){
$return = collect($item)->forget(['categorys', 'plan_details'])->all();
$return['plans'] = $item['plan_details'];
return $return;
})->toArray();
$category = $item[0]['categorys'][0];
$category['categorys'] = $sub;
return $category;
});
return response()->json($PlanDetail);
Output :
[
{
"id": 1,
"title": "category 1",
"categorys": [
{
"id": 5,
"subcategor_name": "regular",
"plans": [
{
"id": 6,
"details": "plan1 reg"
}
]
},
{
"id": 6,
"subcategor_name": "primum",
"plans": [
{
"id": 7,
"details": "plan2 reg2"
}
]
}
]
},
{
"id": 2,
"title": "category 2",
"categorys": [
{
"id": 7,
"subcategor_name": "cat2 reg",
"plans": [
{
"id": 8,
"details": "plan1"
}
]
}
]
}
]

Related

How to merge object and array in one controller laravel

I got like this
[
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
[
{
"IDCollection": 5,
"NameCollection": "Phone",
"Description": "my description",
}
],
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 379000,
"ImagePath": "samsung.png"
},
[
{
"IDCollection": 5,
"NameCollection": "Phone",
"Description": "my description",
}
],
But I want like this:
{
"IDCollection": 5,
"NameCollection": "Phone",
"ProductList": [
{
"NameProduct": "iphone",
"IDProduct": 1,
"ListPrice": 100000,
"ImagePath": "iphone.png"
},
{
"NameProduct": "SamSung",
"IDProduct": 2,
"ListPrice": 100000,
"ImagePath": "samsung.png"
},
]
}
This is my code:
public function show(int $id)
{
$product=[];
$product_collection = CollectionProduct::where('IDCollection',$id)->get();
$collection = Collection::where('IDCollection',$id)->get();
foreach ($product_collection as $items) {
$x = Product::select('NameProduct','IDProduct','ListPrice')->find($items['IDProduct']);
$x->ImagePath = ProductImage::where('IDProduct',$items['IDProduct'])->first()['Path'];
array_push($product, $x,$collection);
}
return response()->json($product);
}
and idea how do that ?
You can use Eager Loading to get the relationships of CollectionProduct. https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
For help you with the code I need to see your relationships of the DB but I think this can help you:
public function show(int $id)
{
$product_collection = CollectionProduct::with('collection.product.productImage')
->where('IDCollection',$id)
->get();
return response()->json($product_collection);
}

Laravel createMany error on nested relation

This is in relation to this question. I'm having this error:
TypeError
Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, int given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 920
While inserting data using createMany. This is the form request data:
{
"name": "My Order",
"orders": [
{
"date": "2022-05-17",
"product_id": [1],
"price": 1
},
{
"start_date": "2022-05-18",
"product_id": [2],
"price": 2
}
]
}
This is the store method:
$order = auth()->user()->orders()->create($request->validated());
$order_subs = $order->subOrders()->createMany($request->orders);
$order_sub_items = $request->only('orders')['orders'];
foreach ($order_subs as $key => $value) {
$value->subOrderProducts()->createMany([$order_sub_items[$key]);
}
However, if the product_id is not an array, it will store properly. Sample form request data:
{
"name": "My Order",
"orders": [
{
"date": "2022-05-17",
"product_id": 1,
"price": 1
},
{
"start_date": "2022-05-18",
"product_id": 2,
"price": 2
}
]
}
How to fix this error?

change hasManyThrough() relation attribute name through accessor

I have 3 Models
Campaign PK(id)
CampaignMedium FK(campaign_id)
AccountReceivable FK(campaign_medium_id) (has an amount column)
Controller function:
public function all()
{
return Campaign::with(['customer', 'receivedPayments'])->get();
}
In Campaign Model relationships are defined as follows:
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function accountReceivable()
{
return $this->hasManyThrough(AccountReceivable::class, CampaignMedium::class);
}
public function receivedPayments()
{
return $this->accountReceivable()
->selectRaw('sum(account_receivables.amount) as total')
->groupBy('campaign_id');
}
public function getReceivedPaymentsAttribute()
{
if (!array_key_exists('receivedPayments', $this->relations)) {
$this->load('receivedPayments');
}
$relation = $this->getRelation('receivedPayments')->first();
return ($relation) ? $relation->total : 0;
}
Final Output:
{
"data": [
{
"id": 8,
"name": "example",
"image": "campaign/90375849f6c3cc6b0e542a0e3e6295b890375849f6c3cc6b0e542a0e3e6295b8.jpeg",
"amount": 10,
"description": "saddsa",
"start_at": "2019-02-12 00:00:00",
"end_at": "2019-02-12 00:00:00",
"due_at": "2019-02-12 00:00:00",
"status": "active",
"customer": {
"id": 1,
"name": "test",
"email": "info#test.com",
"image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
"address": "sample address"
},
"received_payments": [
{
"total": "700",
"laravel_through_key": 8
}
]
},
{
"id": 9,
"name": "example",
"image": "campaign/fff9fadc92a809513dc28134379851aafff9fadc92a809513dc28134379851aa.jpeg",
"amount": 10,
"description": "saddsa",
"start_at": "2019-02-12 00:00:00",
"end_at": "2019-02-12 00:00:00",
"due_at": "2019-02-12 00:00:00",
"status": "active",
"customer": {
"id": 1,
"name": "test",
"email": "info#test.com",
"image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
"address": "sample address"
},
"received_payments": []
}
]
}
summary: trying to get the sum of AccountReceivable amount attribute, which is working fine but the getReceivedPaymentsAttribute() isn't working which needs to return the total value only. also can anyone please help me to explain why laravel_through_key is added with received_payments?
I've never tried to use an attribute modifier to modify a relation this way. You are overriding the expected result of receivedPayments(). You might be better off to define a separate attribute like so:
public function getSumReceivedPaymentsAttribute()
{
// ...your code...
}
Now you can access the attribute using $model->sum_received_payments or always preload it using:
// model.php
protected $appends = ['sum_received_payments'];

how to return a json response based on database relationship

I'm quite new to Laravel,
Let's say I have 2 tables: main_sport and sub_sport. These two tables have a one-to-many relationship. 1 sport can have many sub sports.
I want the following json format
{
"success": "1",
"sports": [
"id": 1,
"name_of_categories": "Popular Sports",
"sub_sports:[
{
"id": 1,
"name_sub_sport_category": "Badminton"
},
{
"id": 2,
"name_sub_sport_category": "Football"
},
{
"id": 3,
"name_sub_sport_category": "Cricket"
},
]
]
"sports":[
"id": 2,
"name_of_categories": "Team Sports",
"sub_sports:[
{
"id": 4,
"name_sub_sport_category": "Badminton"
},
{
"id": 5,
"name_sub_sport_category": "Football"
},
]
]
}
I try for this function and i am getting following result
public function fetch()
{
$query= DB::table('details')
->join('table_sub_sport_category','table_sub_sport_category.id','=','details.sub_id')
->join('table_main_sport_category','table_main_sport_category.id','=','details.main_id')
->select(DB::raw('table_main_sport_category.id as id'),'table_main_sport_category.name_of_categories','table_sub_sport_category.name_sub_sport_category')
->get()
return response()->json(['success' =>'1','data'=>$query]);
}
{
"success": "1",
"data": [
{
"id": 1,
"name_of_categories": "Popular Sports",
"name_sub_sport_category": "Badminton"
},
{
"id": 1,
"name_of_categories": "Popular Sports",
"name_sub_sport_category": "Football"
},
{
"id": 1,
"name_of_categories": "Popular Sports",
"name_sub_sport_category": "Cricket"
},
]
}
Could you help me to get the desired result?
You should define sub_sport in the main sport Model like this:
class Sport extends Model{
public function sub_sport(){
return $this->hasMany(SubSport::class);
}
}
And in your controller you should write this:
$data = Sport::with('sub_sport')->get();
Use below code
$query= DB::table('details')
->join('table_sub_sport_category','table_sub_sport_category.id','=','details.sub_id')
->join('table_main_sport_category','table_main_sport_category.id','=','details.main_id')
->select(DB::raw('table_main_sport_category.id as id'),'table_main_sport_category.name_of_categories','table_sub_sport_category.name_sub_sport_category')
->get()
return Response::json([
'status' => 'error',
'sports' => $query
], 200);

Rethinkdb: Calculate tag occurrence per user

My table contains documents that look like this:
[{ user: {
key: '100'
},
product: {
name: 'Product 1',
tags: [ 'tag1', 'tag2' ],
}
}, { user: {
key: '100'
},
product: {
name: 'Product 1',
tags: [ 'tag1', 'tag3' ],
}
}, ...]
I would like to create a query which would
groupe documents by the user.key field (1 document per user on result),
the product.tags would be an object (instead of array) with tag occurrences count for each tag.
Result example:
[ { user: {
key: '100'
},
product: {
name: 'Product 1',
tags: {
tag1: 2, // tag1 found 2x for user.key=100
tag2: 1, // tag2 found 1x for user.key=100
tag3: 1
}
}
}, ...]
I think I could do this by mapping and reducing but I have problems - I'm using rethinkdb for the first time.
Here's a way to do it:
// Group by user key
r.table('30400911').group(r.row('user')('key'))
// Only get the product info inside the reduction
.map(r.row('product'))
.ungroup()
.map(function (row) {
return {
user: row('group'),
// Group by name
products: row('reduction').group('name').ungroup().map(function (row) {
return {
name: row('group'),
// Convert array of tags into key value pairs
tags: r.object(r.args(row('reduction').concatMap(function (row) {
return row('tags')
}).group(function (row) {
return row;
}).count().ungroup().concatMap(function (row) {
return [row('group'), row('reduction')]
})))
}
})
}
})
For the following data:
{
"id": "0565e91a-01ca-4ba3-b4d5-1043c918c79d" ,
"product": {
"name": "Product 2" ,
"tags": [
"tag1" ,
"tag3"
]
} ,
"user": {
"key": "100"
}
} {
"id": "39999c9f-bbef-4cb7-9311-2516ca8f9ba1" ,
"product": {
"name": "Product 1" ,
"tags": [
"tag1" ,
"tag3"
]
} ,
"user": {
"key": "100"
}
} {
"id": "566f3b79-01bf-4c29-8a9c-fd472431eeb6" ,
"product": {
"name": "Product 1" ,
"tags": [
"tag1" ,
"tag2"
]
} ,
"user": {
"key": "100"
}
} {
"id": "8e95c467-cedc-4734-ad4d-a1f7a371efd5" ,
"product": {
"name": "Product 1" ,
"tags": [
"tag1" ,
"tag2"
]
} ,
"user": {
"key": "200"
}
}
The results would be:
[
{
"products": [
{
"name": "Product 1" ,
"tags": {
"tag1": 2 ,
"tag2": 1 ,
"tag3": 1
}
}, {
"name": "Product 2" ,
"tags": {
"tag1": 1 ,
"tag3": 1
}
}
],
"user": "100"
} ,
{
"products": [
{
"name": "Product 1" ,
"tags": {
"tag1": 1 ,
"tag2": 1
}
}
] ,
"user": "200"
}
]

Resources