As part of a larger query with dynamically-generated elements, I need to do a left join and count. This is the query I need.
SELECT slug, name, count(client_tests.id) AS test_count
FROM clients
LEFT JOIN client_tests ON clients.id = client_tests.client_id
GROUP BY clients.id;
I've tried to build a join query, but Lithium seems to be expecting the join to be part of a relationship (no relationships are defined), as shown below (ignoring the count for now).
$join = new Query(array(
'source' => 'client_tests',
'model' => '\app\models\ClientTest',
'type' => 'LEFT',
'constraint' => array('Client.id' => 'ClientTest.client_id'),
));
$clients = Client::all(array(
'conditions' => $conditions,
'group' => 'Client.id',
'joins' => array($join)
));
This results in Notice: Undefined index: ClientTest in /usr/local/www/oars/libraries/lithium/data/collection/RecordSet.php on line 340
, which seems to be relationship-related code.
If I do define a hasMany
relationship between Client and ClientTest, which will handle building the left join for me, is there a way to get the Client fields and the count?
$clients = Client::all(array(
'fields' => array('slug', 'name', 'count(ClientTest.test_id) as test_count'),
'conditions' => $conditions,
'group' => 'Client.id',
'with' => 'ClientTest'
));
This results in ( ! ) Notice: Undefined index: count(ClientTest in /usr/local/www/oars/libraries/lithium/data/source/Database.php on line 650
, so either it's not possible or I'm using the wrong syntax.
I could simply issue the query directly with Client::connection()->read($sql)
, but as there are dynamic elements to the query, I'd have to build the SQL anyway.
Is there a way to get the above methods to work, or should I go with manually building the SQL?