Laravel 4 Query groupBy: all columns from table - php

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.

Related

Can't get result from where condition with variables in laravel

this is how i'm trying to get the type of certificate with where condition , but still recieve
nothing from this query:
$res= student::find($student, ['typecertificate']);
$k = certificate::select('id-cer')->where('name-cer','=',$res)->get();
return $k;
Based on your comments, I'm assuming you want to retrieve the field certificateType from the latest record that was inserted in the students table.
You can achieve that without a where clause, by directly using the Eloquent Builder to retrieve only that specific field like this:
Student::latest()->first('certificateType');
But this would give you an Eloquent Collection with one element. If you just want the value (not wrapped in a collection), you can simply retrieve the latest student and get the corresponding field directly:
$certificateType = Student::latest()->first()->certificateType;
I could explain more, but your question is vague and your database schema isn't clear either, so I'd need more information on that as well as what you intend to achieve.
In any case, Laravel's documentation is often a big help: https://laravel.com/docs/9.x/eloquent#retrieving-single-models

Php associative array when joining tables with the same field names

I have this consult and I need the key names of the array I'm obtaining:
SELECT table_1.*, table_2.* FROM... INNER JOIN...
I checked other posts with similar titles and the solution is always to use an alias. This won't work for me because I have too many fields and it would be troublesome to write down every single one.
The problem is, of course, that the field names are the same in both tables.
It wouldn't be a problem if I could simply echo $arr["table_1.field_name"] but it doesn't work.
Yes, I could use the index, like $arr[0], $arr[1], $arr[2]. But if I change the table fields order or add new fields then I'll have to change it in the program and it does not seem like a proper solution either.
Thank you very much in advance.
Use AS to alias the second column. It's always the solution, because it IS the solution!
SELECT table1.mycolumn, table2.mycolumn AS table2column

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 !

How do I get results from a database table based on results from a different table in cakephp?

For example I have the following tables in my database:
People
Groups
And in the People table I have the following columns:
Name
Birthdate
Group
In the Groups table I have the following columns:
Name
Colour
Now I want to fetch results from my database to make a list of all the People.
So I would use this:
$this->set('people', $this->Person->find("all"));
And obviously in my view I would loop through the returned array and display it. Now I also want to find out for each person in the list what Colour and Group name they are (retrieved from the groups table).
How would I go about this in CakePHP.
First make sure your model relationships are defined. Second, you might want to consider using "id" fields for your related tables (I assume you did and maybe just did not include them in your original questions table definitions).
And yes, run debug($this->Person->find("all")) as Elwhis noted to see what your array is dumping out.
And if this is a mission critical application, be sure to use containable instead of recursive to prevent taxing queries to your db.
You have to set the recursive attribute. But I guess it should work with the default value. Put this line in your controller debug($this->Person->find("all")) and check whether the data doesn't already contain you desired group information.
If not, try setting $this->Person->recursive = 1; before calling the find() function
For more information about recursive: http://book.cakephp.org/view/1063/recursive

Echoing a pseudo column value after a COUNT

Please don't beat me if this is elementary. I searched and found disjointed stuff relating to pseudo columns. Nothing spot on about what I need.
Anyway... I have a table with some rows. Each record has a unique ID, an ID that relates to another entity and finally a comment that relates to that last entity.
So, I want to COUNT these rows to basically find what entity has the most comments.
Instead of me explaining the query, I'll print it
SELECT entity_id, COUNT(*) AS amount FROM comments GROUP BY entity_id ORDER BY amount DESC
The query does just what I want, but I want to echo the values from that pseudo column, 'amount'
Can it be done, or should I use another method like mysql_num_rows?
Thank you!!!
It's just the same as with the other column – you use the mysql_fetch_* family.
Note that moving to the Mysqli extension is encouraged. See here why.
Once you have the row in, say, $row, you can simply use the value of $row['amount'].

Categories