Hi
I need help to pass a query from SQL to yii2 ORM.
SELECT b.name, COUNT(a.position_id) as cant_users, b.institution_id as institucion
from tb_user_positions as a
JOIN tb_positions b ON b.id = a.position_id
where b.institution_id = 850
group By b.name;
my goal is get all users that belongs to Position and show in positions index view
Position name and its respective counter of users that have this position (marked column)
here an image
Would you please explain what is the problem you are trying to solve first?
If all you want to do is display some results of the query then I suggest you create method in your AR that does the counting and then call it on view.
Here is an example
class SomeModel extends ActiveRecord
{
//normal AR stuffs here
public function getPositionCount()
{
$sql = 'SELECT b.name, COUNT(a.position_id) as cant_users, b.institution_id as institucion FROM tb_user_positions as a
JOIN tb_positions b ON b.id = a.position_id where b.institution_id = 850 group By b.name;'
$count = self::getDb()->createCommand($sql)->queryScalar();
return intval($count);
}
}
I resolve it with your example.
I did a similar query in the model, to get only active users, and then, I called from the column with $model->activeUserPositions