Mysql
 sql >> Database >  >> RDS >> Mysql

Includi, Seleziona, Ordina, Limita da più modelli (singola query)

Ecco come ho incluso tutti i modelli necessari, questa query viene tradotta in 5 query sql poiché il preload non si unisce (viene eseguito in una query separata).

Message.joins("LEFT JOIN messages AS m ON messages.id != m.id 
              AND m.conversation_id = messages.conversation_id 
              AND messages.created_at < m.created_at")
       .where('m.id IS NULL')
       .joins("INNER JOIN conversation_participants AS cp 
              ON cp.conversation_id = messages.conversation_id 
              AND cp.user_id = #{user_id}")
       .order("cp.seen, cp.updated_at DESC")
       .limit(5)
       .includes(:sender)
       .includes(conversation: [{conversation_participants: :user}])