Eloquent查询构建复杂查询以获取在同一表中的2个不同列中搜索ID的唯一记录

时间:2015-02-19 11:15:21

标签: mysql laravel-4 eloquent

我正在将项目迁移到Laravel 4并且我遇到了一个非常复杂的查询,我想将其迁移到正确的Eloquent查询中。

我有一个包含聊天消息的表,名为chat_messages,代表模型Chatmessage

该表包含发件人和收件人列,其用户ID链接到users表和User模型。

在旧版本的应用程序中获取包含原始SQL中所有聊天伙伴的所有用户ID的列表的查询如下:

$sql_allChatPartners = "SELECT DISTINCT chatPartner   
FROM ( SELECT * FROM (
    SELECT cm_receipient AS chatPartner, cm_sent_at
    FROM chat_messages WHERE cm_sender = '".$me->userID."'
    UNION
    SELECT cm_sender AS chatPartner, cm_sent_at
    FROM chat_messages WHERE cm_receipient = '".$me->userID."'
) whateva ORDER BY whateva.cm_sent_at DESC ) other";

很抱歉命名"假"表whateva和其他: - )

任何人都可以通过Eloquent Querybuilder为我做正确的方向吗?

以正确的顺序获取chatPartner ID列表非常重要,其中最后一条聊天消息已作为第一个chatPartner进行交换。而chatPartner中最长的不活动时间是最后一个条目。

这是我在用户模型中到目前为止所得到的......

public function allopenchats(){
 $asSender = Chatmessage::where('sender', $this->id)->select('receipient as chatPartner, created_at');
 $asBoth = Chatmessage::where('receipient', $this->id)->select('sender as chatPartner, created_at')
              ->union($asSender)->orderBy('created_at', 'desc')->get();
}

我在新数据库中为新版本重新命名了cm_receipientreceipientcm_sendersendersent_at的列

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

你的SQL可以改为:

    SELECT IF (cm_receipient = '10', cm_sender, IF (cm_sender = '10',cm_receipient, 'no')) AS chatPartner, cm_sent_at
FROM chat_messages
WHERE cm_receipient = '10' OR cm_sender = '10'
GROUP BY chatPartner
HAVING chatPartner != 'no'

按cm_sent_at DESC排序

在orm:

Chatmessage::where('sender','=',$this->id)
    ->orWhere('receipient','=',$this->id)
    ->select(DB::raw('IF (receipient = '.$this->id.', sender, IF (sender = '.$this->id.',receipient, 'no' )) AS chatPartner'), 'created_at')
    ->groupBy('chatPartner')
    ->having('chatPartner', '!=', 'no')
    ->orderBy('created_at', 'desc')
    ->get();

答案 1 :(得分:0)

非常感谢Vitalik_74,没有他,我不会走得那么远。 现在这是最终查询,虽然它不在ORM中,但它工作正常并且给了我需要的结果。

$result = DB::select("SELECT * 
            FROM (
               SELECT IF( receipient =  '".$this->id."', sender, IF( sender =  '".$this->id."', receipient,  'no' ) ) AS chatPartner, created_at
               FROM chatmessages
               WHERE receipient =  '".$this->id."'
               OR sender =  '".$this->id."'
               HAVING chatPartner !=  'no'
               ORDER BY created_at DESC
            )whateva
            GROUP BY whateva.chatPartner
            ORDER BY whateva.created_at DESC"); 

如果有人可以使用Laravel查询生成器进行此查询,我很乐意看到它。现在我就这样离开了。