Laravel GroupBy Issue - php

I am looking for a way to return all fields that match together. For example, I have a player_name column, I'm looking to return all rows where the player names match. One player's name will return a collection of their results, and so on and so on for however many there are.
This is what I have tried so far
$test = DB::table('approved_g_r_p_s')
->select('player_name', 'cost')
->groupBy('player_name')
->get();
However it only returned one result from each.
One of player A's fields
One of player B's fields
Despite there being multiple others it has only returned one. Any suggestions?

It looks like you need to add the fields that interest you to the groupBy, something like this:
$test = DB::table('approved_g_r_p_s')
->select('player_name', 'cost')
->groupBy('player_name', 'cost')
->get();

Related

how to get the records of a list through an array of id's Laravel

Currently I have two tables, the typical master - detail, what I get is an array of id's from the detail table, [1,2,3,4,5, ...], from this I want to generate a grouping to obtain the details grouped by the master
Master
public function details()
{
return $this->hasMany('App\Models\Detail', 'detail_id');
}
Detail
public function master()
{
return $this->belongsTo('App\Models\Master', 'master_id');
}
Id's [1,2,3,4,5..]
my attempt to get the result, but they are not grouped
return Detail::whereIn('id', $array)->with(['master' => function($query){
$query->groupBy('name');
}])->get();
My question, It is not a duplicate, what makes that question is to get ids which we already have, what I want is to group. It is not correct to close;)
In summary, I don't believe that Eloquent supports groupBy (you'll have to write your own query); and you're not grouping all of the columns.
Your query is not modifying the columns to be selected, so laravel will be selecting all of them; and as such something unique like your IDs will be breaking up the groups. You either need to be explicit about what you're selecting to enable the groups, or explicit about how to summarise the other columns.
The examples on the docs all show customised select queries, with the exception of those specifically under the heading 'groupBy / Having', which is probably a failure of the docs.
But note the other examples, such as this one, that applies grouping functions to all selected columns:
$users = DB::table('users')
// count is a grouping function; status is grouped below
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Is grouping what you really want? Grouping summarises the table, for example by provided totals, or counts, or unique 'names'. If so, you'll need to modify the query manually, like the example above.
If you just want to order them by 'name' (i.e. group them together) then you want the orderBy function. In which case, you'd modify your code as follows:
return Detail::whereIn('id', $array)
->with('master')
->groupBy('name')
->get();
Whilst I don't think it matters here, you may wish to consider whether name is a unique column name between the master and detail tables.

Doctrine Query Builder : Result returning array of two times the same result

I'm currently working on a Symfony project, using Doctrine to manage entities.
I have a table named User, containing a few columns, and then another table named Tag, containing a foreign key to that User table with a ManyToOne relation based on the user id, and a single other column named value.
In my app, I need to find a list of users, depending on one of the Tag row, AND the value of one of the User's column. Let's resume :
Select all users where user.value equals somevalue AND Tag.value equals anothervalue.
As I never used Symfony nor Doctrine before this project, I searched into Doctrine documentation and found about the Query Builder. So, I did this :
EDIT : The way I was doing it was kinda weird, so I modified it and here is the result :
public function findByTagAndApp($tag, $app)
{
$em = $this->getEntityManager();
$qb = $em
->getRepository('APIBundle:User')
->createQueryBuilder('u')
->leftJoin('APIBundle\Entity\Tag', 't')
->where('u.application = :app')
->andWhere('t.tag = :tag')
->setParameter('tag', $tag)
->setParameter('app', $app)
;
$users = $qb->getQuery()->getResult();
return $users;
}
And it seems like it works, but in a strange way. Instead of returning an array of User items, which is what I want, it returns an array of array of User items. The first array is always containing two entries, and these two entries are always identical : they are the array I need, without a single difference.
I tried to do return $users[0] instead of just users, and then I can manipulate my User entities the intended way. I could keep it this way as it is working, but I'd really like to know why it returns an unneeded array of array instead of just the array I want. It might be my query, but I'm not sure how to modify it to get only the Users I want.
Any clues on why it behave like this would be really appreciated, as I'm still learning about Doctrine. Thanks !
EDIT² : Nevermind, this query seems completely incorrect too, as I got all users according to the $app value, but it seems like it never check if there is a row in the Tag table with a value of somevalue associated to a foreign key of the User table..
I don't know exactly why it is but..
I think you have to mention from() like ->from('User', 'u')
for extra you can find here
After a few hours of tweaking, I figured it out using SQL statement on PhpMyAdmin, so I could notice that there was a LOT of things that I was doing wrong :
First, the join was not correct. My goal was to collect users that had a certain value in their own table, AND a value from the Tag table. Using a left join, I was collecting users with their own value OR a the value from the Tag table.
Second : The $app value I was passing was an object of type Application (the Application field in my User table is a foreign key), and the query builder didn't know what to do with it. Passing the app_id instead of the app object solved the problem.
Third : The way I collected result was wrong. Obviously, this query returns an array of User objects. And as I execute this query multiple times in a row, I had an array on which I used array_push to fill it with the data, thinking that pushing array1 with array2 would put array2 values into array1, but it was just putting array2 into array1, resulting to that array of arrays that was the initial problem. Using array_merge instead of array_push, I am now able to collect all the results from the queries into a single array. A little array_unique on that to avoid redundancy, and everything is working as expected.
Thanks to everyone who replied !

Cakephp - get database data from not associated models

I wanted to ask, how can i get data from one table and use this in other find.
For example, i have films table.
I want to get highest rated 3 films. Result should return 3 ID's.
Now, i want to create other query from not associated table, and pass this 3 ID's as "conditions" to find data in other table.
I dont want to use associations, because, data is stored in many databases, and this is problematic.
Thank You.
Once you've got your film IDs you can use in to filter the results from your other Model:-
$filmIds = ['32','55','75'];
$query = TableRegistry::get('Model')->find()
->where(function ($exp, $q) use ($filmIds) {
return $exp->in('film_id', $filmIds);
});
// WHERE film_id IN ('32','55','75')
Check out the docs section on advanced conditions.
If you need to get your film IDs into the correct format (i.e. that shown in the example code) you can use Hash::extract() on the results from your previous query.
if your cakephp version 3.x you can use subqueries in fairly intuitive way
$films = TableRegistry::get('Films')->find('highestRated')
->select(['id'])
->limlt(3);
$query = $related->find()
->where(['id' => $films]);
Subqueries are accepted anywhere a query expression can be used. For example, in the select() and join() methods. http://book.cakephp.org/3.0/en/orm/query-builder.html#subqueries

Laravel 4 Query groupBy: all columns from table

I have to call the $model->groupBy(?allcols?) function with all columns as a param.
How should I do this?
Edit: I have all Columns as an Array, so i can't pass them like 'col1','col2',...
I'm asking this because i have this poblem (github) and i found out, that there the prob is on Line 119.
I tried it manually like col1,col2 which worked, but it should by dynamically for all models.
I found this snippet, to get all cols from the current table as an array, but i can only pass a String.
Ok, if I'm understanding your edit correctly, you've got an array of column names you wish to group by. If $model is the name of your query, I'd recommend just using a foreach loop and appending each field:
foreach($allcols as $col){
$model->groupBy($col);
}
$model->get();
There is no such function for grouping all columns but you may use groupBy(col1, col2, ...), for example, if you have a posts table then you may use:
DB::table('posts')->groupBy('col1', 'col2')->get();
Or using Eloquent Model, for example a Post model:
Post::groupBy('col1', 'col2')->get();
If all you're trying to do is get rid of duplicate records (which is all that groupBy(all) would do as far as I can envision), you could also just use $model->distinct() instead. However, unless you add a select() to exclude the id field, you're going to wind up with the full recordset with no grouping, as by definition the id is unique to each record and thus won't collapse across records by either manner.

Searching and filtering / refining database results in Laravel 4

I'm looking for a way to search and filter a database table / Eloquent model through the query string in Laravel 4.
I have a table named houses with the columns named: price, name, hasCoffeeMachineand hasStove
I want the user to be able to do something like: http://example.com?name=test&hasCoffeeMachine=1
Which will get all the rows where the name is "test" and they have a coffee machine.
I want the user to be able to add URL parameters based on the filter they desire. What is the best way to account for all the possible combinations of query strings to return the correct results from the table?
$houses = new House;
if(Input::get('name'))
$houses->where('name', '=', Input::get('name'));
if(Input::get('hasCoffeeMachine'))
$houses->where('hasCoffeeMachine', '=', Input::get('hasCoffeeMachine'));
// Keep adding more for every filter you have
// Don't do this till you are done adding filters.
$houses = $houses->get();
alternatively you could build and pass in an array into the where clause https://laravel.com/docs/5.2/queries#where-clauses
$houses = $houses->where([
['hasCoffeeMachine',1],
['price','<','1000'],
])->get();
You can build your array with any conditional statements.

Categories