How to get multiple whereBetween records in Laravel - php

I'm building a small application on Laravel 5.4 where I'm having data sets to are being fetched from the relationship something like this:
$meetings = Company::where('name', 'Atlanta Ltd')
->withCount(['interactions as investors'=> function ($q) {
$q
->whereBetween('schedule', [Carbon::now()->subMonths(6), Carbon::now()->subMonths(1)])
->whereHas('contactsAssociation', function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
});
}])->get()
->transform(function ($company) {
$company->investors_count = $company->interactions
->pluck('investors_count')
->sum();
return $company;
});
Currently I'm getting the number of interaction as investor_counts between that particular date, I want to fetch the counts between certain date fields, i.e. suppose I want to have the data to be fetched for consecutive 6 months, I mean data of 6 different months something like this:
->whereBetween('schedule', [Carbon::now()->subMonths(6), Carbon::now()->subMonths(5)])
and
->whereBetween('schedule', [Carbon::now()->subMonths(5), Carbon::now()->subMonths(4)])
and
->whereBetween('schedule', [Carbon::now()->subMonths(4), Carbon::now()->subMonths(3)])
And the list goes on similar to above differences. And I don't want to implement multiple foreach loops, is there any way out with Laravel Collection where I can manipulate such data the get the output. Please guide me. Thanks.
Edit:
Let me explain in better way, currently I'm using this code to get my desired data:
public function investorGraphData(Request $request)
{
$weekInvestorData = $weekResearchData = [];
if($request->timeFormat == 'month')
{
for($i=0; $i<6; $i++)
{
$meetings = Company::where('name', $request->client)
->withCount(['interactions as investors'=> function ($q) use($i) {
$q
->whereBetween('schedule', [Carbon::now()->subMonth($i+1), Carbon::now()->subMonth($i)])
->whereHas('contactsAssociation', function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
});
}])
->withCount(['interactions as research' => function($q) use($i) {
$q
->whereBetween('schedule', [Carbon::now()->subMonth($i+1), Carbon::now()->subMonth($i)])
->whereHas('contactsAssociation', function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Research');
});
});
}])
->get();
$weekInvestorData[] = $meetings[0]->investors_count;
$weekResearchData[] = $meetings[0]->research_count;
}
return response()->json(['investor' => $weekInvestorData, 'research' => $weekResearchData], 200);
}
elseif ($request->timeFormat == 'week')
{
for($i=0; $i<6; $i++)
{
$meetings = Company::where('name', $request->client)
->withCount(['interactions as investors'=> function ($q) use($i) {
$q
->whereBetween('schedule', [Carbon::now()->subWeek($i+1), Carbon::now()->subWeek($i)])
->whereHas('contactsAssociation', function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
});
}])
->withCount(['interactions as research' => function($q) use($i) {
$q
->whereBetween('schedule', [Carbon::now()->subWeek($i+1), Carbon::now()->subWeek($i)])
->whereHas('contactsAssociation', function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Research');
});
});
}])
->get();
$weekInvestorData[] = $meetings[0]->investors_count;
$weekResearchData[] = $meetings[0]->research_count;
}
return response()->json(['investor' => $weekInvestorData, 'research' => $weekResearchData], 200);
}
else
return response()->json(['message' => 'No input given'], 200);
}
Is there any way to shorten this code through collection?

you may try to give column as different name,
For example :
$meetings = Company::where('name', 'Atlanta Ltd')
->withCount(['interactions as investors'=> function ($q) {
$q
->whereBetween('schedule as schedule6to5', [Carbon::now()->subMonths(6), Carbon::now()->subMonths(5)])
->whereBetween('schedule as schedule5to4', [Carbon::now()->subMonths(5), Carbon::now()->subMonths(4)])
->whereBetween('schedule as schedule4to3', [Carbon::now()->subMonths(4), Carbon::now()->subMonths(3)])
->whereHas('contactsAssociation', function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
});
}])->get()
->transform(function ($company) {
$company->investors_count = $company->interactions
->pluck('investors_count')
->sum();
return $company;
});
May be this will work.

Related

Laravel relationship data with different tables nased on conditions

i am working on a snippet but i have to check another table if that customer data exists return the data if the customer data does not exist on the employment table also return the data based on the former check then ignore the rest but if it does i want to use the condition specified to check and return that data. Here's what i have tried.
Customers::query()
->distinct('id')
->whereHas('quote')
->where(
function ($query) {
$query->whereHas('profile', function ($query) {
$query->where(function ($query) {
$query->whereNull('nin')->WhereNull('bvn');
})->orWhere(function ($query) {
$query->whereNotNull('nin')->whereNotNull('bvn');
});
})->orWhereHas('employment', function ($query) {
$query->where(function ($query) {
$query->whereNull('bank_statement_url')->WhereNull('mono_account_statement_url');
})->orWhere(function ($query) {
$query->whereNotNull('bank_statement_url')->whereNotNull('mono_account_statement_url');
});
});
}
)->paginate(30);
I cleaned up your code a bit as well as changing your orWhereHas() to whereHas():
Customers::query()
->distinct('id')
->whereHas('quote')
->whereHas('profile', function ($query) {
$query->where(function ($query) {
$query->whereNull('nin')->WhereNull('bvn');
})->orWhere(function ($query) {
$query->whereNotNull('nin')->whereNotNull('bvn');
});
})->whereHas('employment', function ($query) {
$query->where(function ($query) {
$query->whereNull('bank_statement_url')
->whereNull('mono_account_statement_url');
})->orWhere(function ($query) {
$query->whereNotNull('bank_statement_url')
->whereNotNull('mono_account_statement_url');
});
}
)->paginate(30);

Laravel Eloquent Model return data if relatioship has data

Good day, I'm trying to return data from Eloquent Model with relationships.
Is there a way to ( skip / not return) orders where relationship returns an empty array as result?
Order::with(['products' => function ($query) {
$query->whereHas('progress', function ($query) {
$query->where('progress_id', 30)->orWhereBetween('progress_id', [60, 90]);
});
$query->whereHas('product', function ($query) {
$query->where('vendor_id', 3);
})->with(['product' => function ($query) {
$query->select('id', 'identifier', 'reference', 'shipping_id');
}]);
$query->select('id', 'order_id', 'product_id', 'quantity');
}])
->whereHas('products')
->where('status_id', '=', 15)
->select('orders.id', 'orders.customer_id', 'orders.created_at')
->get();
So in this case I don't want to get that order because there are no products with it.
Also I don't understand why am I even getting results there are orders with status_id = 15 but non for vendor_id = 3.
How to do it? Thank you for reading.
Try this
Order::whereHas('products')->with(['products' => function ($query) {
$query->whereHas('progress', function ($query) {
$query->where('progress_id', 30)->orWhereBetween('progress_id', [60, 90]);
});
$query->whereHas('product', function ($query) {
$query->where('vendor_id', 3);
})->with(['product' => function ($query) {
$query->select('id', 'identifier', 'reference', 'shipping_id');
}]);
$query->select('id', 'order_id', 'product_id', 'quantity');
}])->where('status_id', '=', 15)
->select('orders.id', 'orders.customer_id', 'orders.created_at')
->get();
Lets try this code:
Order::has('product', '>=', 1)->get();
Try this:
Order::whereHas('products' => function ($query) {
$query->whereHas('progress', function ($query) {
$query->where('progress_id', 30)->orWhereBetween('progress_id', [60, 90]);
});
$query->whereHas('product', function ($query) {
$query->where('vendor_id', 3);
});
// $query->select('id', 'order_id', 'product_id', 'quantity'); // This line will cause error
}])->with(['products', 'products.product:id,identifier,reference,shipping_id,vendor_id'])
->where('status_id', 15)
->get();

How to use laravel collection methods

I'm trying to query a nested relation and getting the count of distant model count, I'm transforming this to a variable but it is not happening:
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Research');
});
}]);
}])
->get()
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
->collapse()
->sum();
});
When I try to dd($companies) or even return $companies I get null values placed in each array index
But when I do dd($company) inside transform
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
->collapse()
->sum();
dd($company);
});
I get the single collection which states my query is running properly:
If I remove transform part and simply get the collection:
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Research');
});
}]);
}])
->get()
I'm getting the desired output, But I don't know what it is happening after transform execution. In fact it is not plucking and adding the sum, as I'm getting all 0 in the counts.
I've marked them with red. Help me out in this
I think you are missing a return statement in the transform closure.
You need to put return $company statement in transform.

How to use laravel collection helper methods?

I'm trying to build a small application on laravel-5.4 where I'm having a relational query something like this:
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get();
Now I want to collect all the contact_association_counts generated from the query and add it to individual company collection For this I'm using pluck, collapse and sum method, but I don't know it is not calculating as desired. Following is the screenshots:
I get list of collection as following:
Now I get the attributes:
Now relational data:
Now interaction data, where the count belongs:
So for this I tried:
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get()
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
->collapse()
->sum();
return $company;
});
But this is not calculating the counts, all the counts are coming to 0
Help me out in this. Thanks
I believe that your problem is the ->collapse() seeing your example after the ->pluck('interaction.contacts_association_count') you should have a flat array as [1,2,3,4,5] if you apply collapse() to a flat array it returns a void array [] and the sum of a void array is 0
$companies = Company::where('is_client', '=', 1)
// load count on distant model
->with(['interactionSummaries.interaction' => function ($q) {
$q->withCount(['contactsAssociation' => function ($q) {
$q->whereHas('company', function ($q) {
$q->where('type', 'like', 'Investor');
});
}]);
}])
->get()
->transform(function ($company) {
$company->contacts_association_count = $company->interactionSummaries
->pluck('interaction.contacts_association_count')
//->collapse()
->sum();
return $company;
});
I hope it works... good luck!

undefined variable in model method (laravel)

this is my JadwalKlinik method:
public function scopeByParams($query, $params)
{
if( isset($params) ){
$query->whereHas('user', function($q){
$q->where('name', 'LIKE', '%'.$params.'%');
});
}
return $query;
}
$params in query function (line 5) is undefined, why ???
You need the keyword use with your closure
$query->whereHas('user', function($q) use ($params){
$q->where('name', 'LIKE', '%'.$params.'%');
});

Categories