Laravel query builder - Select elements unique or null on specific column - laravel

I have a model Form for table forms. There is a column called guid which can be null, or contain some sort of grouping random hash.
I need to select all forms that have column guid either null or unique in current search. In other words, for repeating guid values in current search I select only first occurence of every guid hash.
I tried:
$results = App\Form::where(... some where clauses .. ).groupBy('guid')
and it's almost ok, but for all rows, where guid == NULL it groups them and selects only one (and I need all of them).
How can I get the unique or null rows either by building proper SQL query or filtering the results in PHP?
Note: I need my $results to be an Illuminate\Database\Eloquent\Builder instance
EDIT:
I fount out that SQL version of query I need is:
SELECT * FROM `forms` WHERE .... GROUP BY IFNULL(guid, id)
What would be equivallent query for Laravel's database query builder?

UPDATE: Using DB::raw
App\Form::where(... conditions ...)
->groupBy(DB::raw("IFNULL('guid', 'id')"));
Or the another way could be:
You can also use whereNotNull, whereNull & at last merge both the collections using merge() like this:
First get the results where guid is grouped by (excluding null guid's here):
$unique_guid_without_null = App\Form::whereNotNull('guid')->groupBy('guid')->get();
Now, get the results where guid is null:
$all_guid_with_null = App\Form::whereNull('guid')->get();
and at last merge both the collections using merge() method:
$filtered_collection = $unique_guid_without_null->merge($all_guid_with_null);
Hope this helps!

For your edited question, you can use raw() as;
->groupBy(DB::raw("IFNULL('guid', 'id')"))
So your final query will be as:
$results = App\Form::where(... some where clauses .. )
->groupBy(DB::raw("IFNULL('guid', 'id')"));
By above query, your $results will be an instance of Illuminate\Database\Eloquent\Builder.

Related

How do I return only the value as a string and not a collection?

This eloquent collection provides this result:
$id = Model::where('s_id', $s_id)->pluck('l_id');
print_r($id)
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => 31242682774
)
)
How do I return only the "31242682774" value as a string and not a collection?
EDIT ANSWER:
All I had to do is:
$id = Model::where('s_id', $s_id)->pluck('l_id')->first();
Any better options?
If you only need a single value, not multiple values, pluck isn't what you want. There is a method called value on Query Builder that returns a single value:
Model::where('s_id', $s_id)->value('l_id');
Laravel 6.x Docs - Query Builder - Retrieving Results - Retrieving A Single Row / Column From A Table value
It compares to when it the process you wanna do it. On the query execution or after. The most common approach would probably be.
$id = Model::where('s_id', $s_id)->first()->l_id;
This will execute after, meaning the query builder will fetch all columns in the row. In general in Laravel you don't that often work with strings and or other abstractions than your model. Model::where('s_id', $s_id)->first() will return your model and select the l_id property on it.
The approach you chosen is the database way, you only select the l_id and return it as a collection and select the first item from there. This is thou a very performance efficient way of doing it since the database does all the work and is very quick at it.
$id = Model::where('s_id', $s_id)->pluck('l_id')->first();
The reason why it is a collection, it is mainly made for selecting multiple id's, so if you query returned multiple rows multiple ids would be returned. Here you can see an example of pluck in conditional queries, where it is most often used.
$teamIds = Team::where('type', 'admin')->pluck('id');
$adminUsers = User::where('team_id', $teamIds)->get();
Your solution is perfect for what you need, just trying to bring clarity on why and a example of how it is often used.

Distinct in Laravel 5 not working properly

I want the distinct names from my database table.The table contains column id and name.
I have tried
$diff=Crud::distinct('name')->get();
$diff=Crud::distinct()->get();
Both of them not worked.They are returning the result with duplicates.Here Crud is my eloquent model.
But when i use
$cnt=Crud::distinct()->count('name'); //returns the correct count
and
$u=Crud::all();
$diff=$u->unique('name'); //returns the distinct names
Why duplicate values are returned while i'm using the distinct? I want distinct names by using distinct.
Thanks.
distinct() doesn't accept arguments. Use one of these options:
$diff = Crud::distinct()->pluck('name');
$diff = Crud::distinct()->get(['name']);
$diff = Crud::distinct()->select('name')->get();

Select one column with where clause Eloquent

Im using Eloquent. But I'm having trouble understanding Eloquent syntax. I have been searching, and trying this cheat sheet: http://cheats.jesse-obrien.ca, but no luck.
How do i perform this SQL query?
SELECT user_id FROM notes WHERE note_id = 1
Thanks!
If you want a single record then use
Note::where('note_id','1')->first(['user_id']);
and for more than one record use
Note::where('note_id','1')->get(['user_id']);
If 'note_id' is the primary key on your model, you can simply use:
Note::find(1)->user_id
Otherwise, you can use any number of syntaxes:
Note::where('note_id', 1)->first()->user_id;
Note::select('user_id')->where('note_id', 1)->first();
Note::whereNoteId(1)->first();
// or get() will give you multiple results if there are multiple
Also note, in any of these examples, you can also just assign the entire object to a variable and just grab the user_id attribute when needed later.
$note = Note::find(1);
// $user_id = $note->user_id;

Write query which run on array by considring sub query in Parse

I need to write a query in such way that the array(collection) is contain only sub query objects.
Suppose we have the two tables as follows:
TableA:
objectId, name
TableB:
objectId, names[array of name: parse pointer collection]
Here is my code which I tried:
// sub query
var subQuery = new Parse.Query('TableA');
subQuery.doesNotExist('name');
// main query
var query = new Parse.Query('TableB');
query.exists("names");
//query.containsAll("names", subQuery); // this means names should contain all subQuery, so this is not use full for me.
query.matchesQuery("names", subQuery);
This code is running fine, but this is not working as I want and also not showing the any error.
It seems that you don't need a subquery per se, but rather to first query your list of names, and then use that in your main query. What you seem to be looking for is: containedIn( key, values ) , as in:
query.containedIn("name", namesFromFirstQuery)

Laravel - When to use ->get()

I'm confused as to when ->get() in Laravel...
E.G. DB::table('users')->find(1) doesn't need ->get() to retrieve the results, neither does User::find(1)
The laravel docs say "...execute the query using the get or first method..."
I've read the Fluent Query Builder and Eloquent docs but don't understand when the usage of get() is required...
Thanks for the help
Since the find() function will always use the primary key for the table, the need for get() is not necessary. Because you can't narrow your selection down and that's why it will always just try to get that record and return it.
But when you're using the Fluent Query Builder you can nest conditions as such:
$userQuery = DB::table('users');
$userQuery->where('email', '=', 'foo#bar.com');
$userQuery->or_where('email', '=', 'bar#foo.com');
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
// Done with building the query
$users = $userQuery->get();
For find(n), you retrieve a row based on the primary key which is 'n'.
For first(), you retrieve the first row among all rows that fit the where clauses.
For get(), you retrieve all the rows that fit the where clauses. (Please note that loops are required to access all the rows or you will get some errors).
find returns one row from the database and represent it as a fluent / eloquent object. e.g. SELECT * FROM users WHERE id = 3 is equivalent to DB::table('users')->find(3);
get returns an array of objects. e.g. SELECT * FROM users WHERE created_at > '2014-10-12' is equivalent to DB::table('users')->where('created_at', '>', '2014-10-12')->get() will return an array of objects containing users where the created at field is newer than 4014-10-12.
The get() method will give you all the values from the database that meet your parameters where as first() gets you just the first result. You use find() and findOrFail() when you are searching for a key. This is how I use them:
When I want all data from a table I use the all() method
Model::all();
When I want to find by the primary key:
Model::find(1)->first();
Or
Model::findOrFail(1)->first();
This will work if there is a row with a primary key of one. It should only retrieve one row so I use first() instead of get(). Remember if you deleted the row that used key 1, or don't have data in your table, your find(1) will fail.
When I am looking for specific data as in a where clause:
Model::where('field', '=', 'value')->get();
When I want only the first value of the data in the where clause.
Model::where('field', '=', 'value')->first();
Basically what you need to understand is that get() return a collection(note that one object can be in the collection but it still a collection) why first() returns the first object from the result of the query(that is it returns an object)
#Take_away
Get() return a collection first() return an object
You can use get() method with latest() method to get the latest record that were recently added to your table
For example
$user=Student::latest()->get();
return all the data in descending order

Resources