Search code examples
phpdoctrine-ormdoctrinegreatest-n-per-groupslim

doctrine dbal get latest chat message per group


when trying make multiple select

$result = $this->qb->select('c.id','c.message','acc.name as chat_from', 'c.chat_to as count')
    ->addSelect("SELECT * FROM chat ORDER BY date_deliver DESC")
        ->from($this->table,'c')
        ->join('c','account','acc', 'c.chat_from = acc.id')
        ->orderBy('date_sent','DESC')
        ->groupby('chat_from')
        ->where('chat_to ='.$id)
        ->execute();
        return $result->fetchAll();

i also tried

$result = $this->qb->select('c.id','c.message','acc.name as chat_from', 'c.chat_to as count')
        ->from("SELECT * FROM chat ORDER BY date_deliver DESC",'c')
        ->join('c','account','acc', 'c.chat_from = acc.id')
        ->orderBy('date_sent','DESC')
        ->groupby('chat_from')
        ->where('chat_to ='.$id)
        ->execute();
        return $result->fetchAll();

I want to display the data by group by and then display the data inside the last entry.

i' used DOCTRINE DBAL


Solution

  • As your question is unclear so i am assuming you need to get the recent chat/message per group, the equivalent SQL for this will be

     SELECT c.id, c.message, a.name as chat_from, c.chat_to as count
     FROM account a
     JOIN chat c ON(c.chat_from = a.id )
     LEFT JOIN chat cc ON(c.chat_from = cc.chat_from AND c.date_sent < cc.date_sent)
     WHERE cc.date_sent IS NULL AND c.chat_to = @id
     ORDER BY c.date_sent DESC
    

    So using doctrine dbal you can write above query as

    $this->qb->select( 'c.id', 'c.message', 'a.name as chat_from', 'c.chat_to as count' )
             ->from( 'account', 'a' )
             ->join( 'a', 'chat', 'c', 'c.chat_from = a.id' )
             ->leftJoin( 'c', 'chat', 'cc', 'c.chat_from = cc.chat_from AND c.date_sent < cc.date_sent' )
             ->where( 'cc.date_sent IS NULL' )
             ->andWhere( 'c.chat_to =' . $id )
             ->orderBy( 'c.date_sent', 'DESC' )
             ->execute();
    

    Again without viewing the sample data and DDL its not a complete solution.

    Reference