GROUP_CONCAT with JOINLEFT in Zend Db Select

2019-05-01 15:06发布

Assuming that I have 2 tables

articles
  id              title
  1               Article 1
  2               Article 2


Images
  id              article_id     image
  1               1              a.png
  2               1              b.png
  3               2              c.png
  4               2              d.png

All that I want is retreive all articles with their images.

For example:

article_id     title           images
1              Article 1       a.png, b.png
2              Article 2       c.png, d.png

How could I do that with Zend_Db_Select?

I tried something like this but had no luck:

$select = $this->getDbTable()->select()->setIntegrityCheck(false)->distinct();
$select->from(array('a'=>'articles'))
  ->joinLeft(array('i'=>'images'),'i.article_id=a.id',array('images'=> new
               Zend_Db_Expr('GROUP_CONCAT(i.image)')));

It returns just only 1 row which 'images' field contains images of both articles.

article_id     title           images
1              Article 1       a.png, b.png, c.png, d.png

What am i doing wrong here?

1条回答
\"骚年 ilove
2楼-- · 2019-05-01 15:51

You have not used group by clause in query.

Try below:

$select->from(array('a'=>'articles'))
  ->joinLeft(
       array('i'=>'images'),
       'i.article_id=a.id',
       array('images'=> new Zend_Db_Expr('GROUP_CONCAT(i.image)')))
  ->group('a.id');
查看更多
登录 后发表回答