I'm trying to replicate an SQL query with Eloquent ORM:
SELECT DISTINCT name, COUNT(name) AS total
FROM tags
WHERE question_id IS NOT NULL
GROUP BY name
ORDER BY name ASC;
Here is my attempt in Eloquent ORM:
$query = Tag::query();
$query->orderBy('name', 'asc');
->groupBy('name');
->select( array('count(name) as total') );
->whereNotNull('question_id');
However, this gives me the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count(name)' in 'field list' (SQL: SELECTCOUNT(name)AStotalFROMtagsWHEREtags.deleted_atIS NULL ANDquestion_idIS NOT NULL GROUP BYnameORDER BYnameASC)
... so clearly I'm not using it properly.
I found a post saying that I should use DB::raw('COUNT(name) as total') but I don't know where DB class is as I'm not working within Laravel. If I need to use this, how can I use it outside Laravel. I tried use for both:
use Illuminate\Database\Connection as DB;
use Illuminate\Database\Query\Builder as DB;
..., as these were the only classes, using grep, I could find to have a public 'function raw' within them. Query/Builder gave me an error, and Connection run OK but perhaps I didn't build the query object correctly as it gives me inconsistent results from running SQL in MySQL shell. Kinda hit a dead end, can anyone offer any help?
Thanks
DBaliases toFluent.Fatal error: Class 'Fluent' not found in /var/www/vhosts/qasystem/qasystem/application/controllers/TagsController.php on line 49