Laravel eloquent Query Reuse extra condition - laravel

I have a query which gives me list of total counts of different items, as:
$data = DB::table($Table1)
->join($table2,$Table1.'.id','=',$Table2.'.device_key')
->where($Table1.'.created_at', '>', $value)
->select('item', DB::raw('count(*) as total'))
->groupBy('item')
->lists('total', 'item');
now i want to fetch same data with extra condition as >where($Table1.'.status', '=', 'SUCCESS') .
how do i do that ??

I don't think you'll get away with anything nice than this.
$query = DB::table($Table1)
->join($table2,$Table1.'.id','=',$Table2.'.device_key')
->where($Table1.'.created_at', '>', $value)
->select('item', DB::raw('count(*) as total'))
->groupBy('item');
$data1 = $query->lists('total', 'rem');
$data2 = $query->where($Table1 . '.status', '=', 'SUCCESS')->lists('total, 'rem');

Use clone to copy the query object for modifications.
$query = DB::table()->where();
$clonedQuery = clone $query;
$clonedQuery->where(..);

Related

How create a subquery with eloquent and laravel with softdeletes

I am using Laravel 7 and Vue.js 2.
I want to retrieve the tasks that are not assigned to a specific user.
I made the following code that works correctly.
$tasks_user = TaskUser::select('task_id')
->where('user_id', $id)
->get();
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $tasks_user)
->distinct()
->get();
By the way to be more elegant I decided to transform the above code into a single query as follows:
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', function($q) use ($id)
{
$q->select('task_id')
->from('task_user')
->where('user_id', $id)
->get();
})
->distinct()
->get();
Unfortunately I discovered that the above query didn't work because it doesn't considers softdeletes.
For example, if the user with id 3 was related with the task 7 but now that row has been deleted with softdeletes in the table task_user, the first code returns also the task with id 7 (correctly) and the second one not (uncorrectly).
So finally, I must do a single query that works as the first code.
Can help?
You can actually combine both approaches. whereNotIn accepts also an Eloquent Query, it doesnt need to be a callback. Try this:
$userRelatedTasksQuery = TaskUser::select('task_id')
->where('user_id', $id);
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $userRelatedTasksQuery)
->distinct()
->get();
Be sure to not use get() at the end of the $userReleatedTasksQuery, as you want the eloquent query instance, not the result.

Laravel Eloquent whereTime() shows null

I have this query to get the events after the the current time and it shows as null. I think the whereTime condition is not working or I have a typo.
$query = Model::where('id', $request->id)
->where('status_id', 1)
->whereTime('event_date', '>=', Carbon::now())
->first();
When I don't have the whereTime condition and check the results, it shows this result
$query = Model::where('id', $request->id)
->where('status_id', 1)
// ->whereTime('event_date', '>=', Carbon::now())
->first();
dd(Carbon::now()->format('Y-m-d H:i:s'), $query->event_date);
Result
"2020-04-15 20:07:43"
"2020-05-23 18:00:00"
If your date like this "2021-03-21 13:33:52" then separate date and time like below
$date = Carbon::parse($timestamp)->format('Y-m-d');
$time = Carbon::parse($timestamp)->toTimeString();
Now you got date and time separated and write query to desire model like below:
User::where('status', 1)->whereDate('created_at', '>=', $date)
->whereTime('created_at', '>', $time)->get();
Hope this will help you. This works for me

Collapse two collections to one in laravel

I need help with collapse my collections.
Its my code
public function showFriends(){
$request1 = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.user_id')
->where([['friend_id', '=',Auth::user()->id],['accepted', '=',true]])
->orWhere([['user_id','=',Auth::user()->id],['accepted','= ',true]])
->get();
$request2 = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.friend_id')
->where([['user_id','=',Auth::user()->id] , ['accepted','=',true]])
->get();
$all = collect($request1,$request2)->collapse();
return $all;
}
Problem is in $all variable because it return empty collection. Thank you for help.
Use the merge method on collections:
$all = $request1->merge($request2);
You can try this
$collection = collect($request1,$request2);
$collapsed = $collection->collapse();
You can also do this potentially with one query by utilizing union:
public function showFriends(){
$query1 = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.user_id')
->where([['friend_id', '=',Auth::user()->id],['accepted', '=',true]])
->orWhere([['user_id','=',Auth::user()->id],['accepted','= ',true]]);
$request = DB::table('friends_users')
->join('users', 'users.id', '=', 'friends_users.friend_id')
->where([['user_id','=',Auth::user()->id] , ['accepted','=',true]])
->union($query1)
->get();
return $request;
return $request->all(); // If you want an array rather than collection
}
The Laravel Documentation on unions:
The query builder also provides a quick way to "union" two queries
together. For example, you may create an initial query and use the
union method to union it with a second query

laravel join query is not working

I have the next query and I want to get the price_types.name but is not returned:
$projects = Project::with('projectsTask')
->select('projects.*',
'price_types.name as name_type'
)
->where('client_id', $client->id)
->join('price_types', 'tasks.type_list', '=', 'price_types.id')
->orderBy('id')
->get();
Here an image query is retrievng
This on picture "type_list" must be string text
Maybe somebody can help me.
Many thanks!
Try this:
$projects = Project::with('projectsTask')
->where('client_id', $client->id)
->join('price_types', 'tasks.type_list', '=', 'price_types.id')
->orderBy('id')
->get([''projects.*',
'price_types.name as name_type'']);
get method receive as parameter an array with fields that you want.
$projects = Project::join('tasks', 'projects.id', '=', 'tasks.project_id')
->select('tasks.*',
'price_types.name as name_type',
'statuses.name as name_status'
)
->where([['client_id', $client->id], ['tasks.status_type', '!=', 2]])
->join('price_types', 'tasks.type_list', '=', 'price_types.id')
->join('statuses', 'tasks.status_type', '=', 'statuses.type')
->orderBy('tasks.id', 'DESC')
->get();

Undefined index: in laravel 4

this is my code ..hope you guys help me because i want to get the value of country['CC_FIPS'] to use in my where statement in city
$local = Input::get('locality');
$country = Input::get('country');
$resultCountry= Country::where('COUNTRY_NAME', '=', $country)->get();
//echo $resultCountry;
$resultCity= City::where('FULL_NAME_ND', '=', $local)
->where('CC_FIPS', '=', $resultCountry['CC_FIPS'])
->get();
}
echo $resultCity;
Problem is that you array $resultCountry does not have any element with index CC_FIPS.
You can see what elements are in this array if you use function dd() as
dd($resultCountry);
$local = Input::get('locality');
$country = Input::get('country');
$resultCountry= Country::where('COUNTRY_NAME', '=', $country)->first()->toArray();
//echo $resultCountry;
$resultCity= City::where('FULL_NAME_ND', '=', $local)
->where('CC_FIPS', '=', $resultCountry['CC_FIPS'])
->get();
}
print_r($resultCity);
Instead of get use first and keep the rest t=of the code as it is.. Hope this helps..
$local = Input::get('locality');
$country = Input::get('country');
$resultCountry= Country::where('COUNTRY_NAME', '=', $country)->first();
//echo $resultCountry;
$resultCity= City::where('FULL_NAME_ND', '=', $local)
->where('CC_FIPS', '=', $resultCountry['CC_FIPS'])
->get();
}
print_r($resultCity);
When Using Get in your first query The result will be returned something like this..
[
[0]=>[
]
]
So instead of Get Use first which will get only one array
Also on the second query you cannot echo the result you need to print_r it
You can convert $resultCountry to an array like this :
$resultCountry= Country::where('COUNTRY_NAME', '=', $country)->get()->toArray();
then $resultCountry['CC_FIPS'] should return your value properly.

Resources