proper usage of queries (Aggregates) in laravel 4.2 - laravel

im trying to get the total count of records that are less than a value in my table so im using this query in laravel 4.2
$critical = DB::table('dbo_modules')
->where('ModuleCountLeft','<','ModuleCriticalLevel')
->count();
and passes it like this
return View::make('ssims.board' ,compact('title','mTotal','critical'));
//please don't mind the others
then receives it in the view page like this
<div>Modules at critical level <span><strong><?= $critical ?></strong></span></div>
unfortunately, im getting zero whereas in my database, i have 2 records where ModuleCountLeft is less than ModuleCriticalLevel
any ideas?
thanks

Hi turns out that i needed to pluck out the value of ModuleCriticalLevel first here is the code
$critical = DB::table('dbo_modules')
->where('ModuleCountLeft' , '<' , DB::table('dbo_modules')->pluck('ModuleCriticalLevel') )
->count();
-thumbs up here-

Related

Laravel groupBy inside with doesnt work properly

Hello guys after searching in the web and laravel docs and similar questions in Stackoverflow(without answers) I finally come here for help
The following query gives me this result
https://drive.google.com/file/d/187XhxyfUUjcIo6y3LufbDIF7T4gZ2LnB/view?usp=sharing
$lotes_query=Lote::with(['salidas' => function ($q) {
$q->select(DB::raw('*,sum(cantidad) as cantidad_total, 0 as precio_total'))->groupBy('inventario_entrada_id')->with('entrada');
}])->whereIn("cod_lote",['1722H','1722H','1822M'])->get();
Just 1 of the json objects have the relantionship salidas and the rest ones show the salidas array empty
However if I change the Query to
$lotes_query=Lote::with(['salidas' => function ($q) {
$q->with('entrada');
}])->whereIn("cod_lote",['1722H','1722H','1822M'])->get();
The results would be
https://drive.google.com/file/d/1CrAVvP9BquG69WMurJVpsXZnw2uqkIl_/view?usp=sharing
On that second query relantionship now exist on all the Lotes however it returns a lot of results for salidas I only need to group by , sum the quantity column (cantidad) to know how much I have spent for each type of food in all my lotes
Any type of help would be highly appreciated it thank you

laravel unique() dont work with paginating

i'm facing with an issue in laravel 5.7.28, i'm trying to get records with all of my fields and paginate them , sadly i got a bug in my code that cause registering users with duplicate phone number(a user registered itself more than one time and of course i fix the bug ) , for now i'm facing with a scenario that i want to fetch my (non-duplicate) distinct users on their phone, and paginate them . here is wishful scenario :
$users = User::distinct('phone')
->doesntHave('carrierUsers')
->doesntHave('thirdparty')
->latest()->paginate(40);
it returns all users (with duplicate phone number), seems distinct function not affected , so i tried unique function :
$users = User::doesntHave('carrierUsers')
->doesntHave('thirdparty')
->latest()->paginate(40)->unique('phone');
it works (for getting non-duplicate) but break paginating functionality
and for
$users = User::doesntHave('carrierUsers')
->doesntHave('thirdparty')
->latest()
->unique('phone')
->paginate(40);
i got error for undefined function on builder , means it works on collections ,
also i tried groupBy (search whole the web for solution) , it makes me confused till when i use it
User::doesntHave('carrierUsers')->doesntHave('thirdparty')
->latest()->groupBy('phone')
->paginate(40);
i got SELECT list is not in GROUP BY clause, is that mean in every phrase in my select statement (for now is all ('*') ) i should use it in my groupBy ?
i mean i need all columns , how can i have all those column in groupBy clause ? whats that mean by the way ?
, error is telling : this is incompatible with sql_mode=only_full_group_by. is she making this happen ? how can i fix it ?
1) excuse me for my english
2) Thanks for reading whole this
3) pleasure to reply and help me
Problem 1: Use distinct
For distinct() method, passing parameters is not supporteds, so distinct(phone) will not works.
You can use ->select('phone')->distinct() instead. However, support unique column is selected.
Problem 2: Use Group By
So if you want to select all columns and unique one column, you can use group by.
And because you are using mysql 5.7+.
The ONLY_FULL_GROUP_BY and STRICT_TRANS_TABLES modes were added in MySQL 5.7.5.
So if you select all columns and group one column, you will get the only_full_group_by error.
There are two options can solve this problem.
Solution1:
Use ANY_VALUE()
User::doesntHave('carrierUsers')->doesntHave('thirdparty')
->latest()
->selectRaw('phone, ANY_VALUE(id) AS id, ANY_VALUE(username) AS username, ...')
->groupBy('phone')
->paginate(40);
Solution2:
In config/database.php configuration, set strict mode to false(This is not very safty):
'mysql' => [
'driver' => 'mysql',
...
'strict' => false,
],

laravel multiple read data

Iam learning laravel.I don't understand how to read multiple data in laravel.
In my Data-table , my value is 1,2,3
my column name is hobby & value is 1,2 . 1 & 2 are related other table, where i stored my hobby name .
suppose ,
id || name
1 || gardening
2 || playing
I want to display
gardening,playing
My controller's Code :-
$interests = DB::table('tbl_interests') ->join('tbl_interest_masters','tbl_interest_masters.interest','=','tbl_interests.id')
->select()
->get();
return view('profile')
->with('interest',$interests);
Don't understand how display data in my view ?
is my code right for read multiple data !!
Note that, i already learn how to read single data with relationship in Laravel.
just remove the select() method from the chain.
$interests = DB::table('tbl_interests')
->join('tbl_interest_masters','tbl_interest_masters.interest','=','tbl_interests.id')
->first();
return view('profile')->with('interest',$interests);
I don't fully understand your question, do you want to return multiple variables?
If so, try this:
return view('YOUR_VIEW', compact('VARIABLE1', 'VARIABLE2'));
If you are using blade, you can use this to display the returned variables:
{{$VARIABLE1}}
Loop through an array:
#foreach($interests as $interest)
{{$interest->name}}
#endforeach

Laravel 5.3 Method distinct does not exist

I am trying to write a query that returns the count of distinct links. However, I keep on getting
Method distinct does not exist
Here is my code
$sample = Sample::all();
$uniqueResumes = $sample->distinct()->select('link')->count();
Please try this :
$uniqueResumes = Sample::select('link')->distinct()->count();

Not getting all the table data while executing the laravel query

Link for table
link for expected result, after group by 'receiver_user_id' and recent time
I have used the laravel query:-
$sub = BaseMessagesHistory::select('messages_history.*')->orderBy('created_at','DESC');
$chats = DB::table(DB::raw("({$sub->toSql()}) as sub"))
->select('receiver_user_id',DB::raw('max(created_at) as recent_time'))
->where('sender_user_id',$userId)
->orwhere('receiver_user_id',$userId)
->groupBy('receiver_user_id')
->havingRaw('max(created_at)')
->latest()->get();
Result:-
I am getting only "recent_time" and "receiver_user_id"
Expectation:- I need whole data from table not only "recent_time" and "receiver_user_id"
So can you please help me out
It will return you only those columns which you mentioned in the select().
In your query, you mentioned only receriver_user_id and recent_time.
->select('receiver_user_id',DB::raw('max(created_at) as recent_time'))
You need to add all those columns in select() which you need.
Or try this ->select('sub.*',DB::raw('max(created_at) as recent_time'))
Hope this helps. Ask in case of doubt.

Resources