0

So I have this query:

select u.*, count(mi.media_id) as media_count
from user as u
left join media_items as mi on mi.user_id = u.user_id
where u.is_enabled = 1 and
group by u.user_type
having media_count > 0;

I'm trying to translate it to a Zend_Db_Select. So far I have everything but the count of the media. This is what I tried:

$select->from(array('u' => 'user'), array('*', new Zend_Db_Expr('COUNT(mi.media_id) AS media_count'))
       ->joinLeft('mi' => 'media_items'), 'mi.user_id = u.user_id')
       ->where('u.is_enabled = 1')
       ->group('u.user_type')
       ->having('media_count > 0');

This gets me the error:

"Mysqli prepare error: Unknown column 'media_count' in 'having clause'"

How do I create this statement the Zend way?

Also, I outputted the query that this created and ran it on MySQLWorkBench and it ran just fine.

Edit I've just tried:

->columns('media_count' => new Zend_Db_Expr('COUNT(mi.media_id)'))

Same error.

kailoon
  • 2,131
  • 1
  • 18
  • 33

1 Answers1

1

This should work properly :

$select->from(array('u' => 'user'), array('*', 'media_count' => 'count(mi.media_id)'))
   ->joinLeft('mi' => 'media_items'), 'mi.user_id = u.user_id')
   ->where('u.is_enabled = 1')
   ->group('u.user_type')
   ->having('media_count > 0');
Fouad Fodail
  • 2,653
  • 1
  • 16
  • 16