如何将这个sql转换成laravel?

5jvtdoz2  于 2021-07-29  发布在  Java
关注(0)|答案(0)|浏览(298)

我有下面的sql查询。它从用户的每个会话中检索所有最新消息。我正在将我的纯php应用程序迁移到laravel,所以我没有很多这方面的经验。我成功地转换了大多数查询,但是这个查询对我来说太复杂了,即使在sql中也是如此。我需要帮助。以下是查询:

SELECT result.id, s.name AS sender, result.sender_id, r.name AS receiver, result.receiver_id, result.sent_at, result.read
                FROM (SELECT t1.*
                        FROM letters AS t1
                        INNER JOIN
                        (
                            SELECT
                                LEAST(sender_id, receiver_id) AS sender_id,
                                GREATEST(sender_id, receiver_id) AS receiver_id,
                                MAX(id) AS max_id
                            FROM letters
                            GROUP BY
                                LEAST(sender_id, receiver_id),
                                GREATEST(sender_id, receiver_id)
                        ) AS t2
                            ON LEAST(t1.sender_id, t1.receiver_id) = t2.sender_id AND
                               GREATEST(t1.sender_id, t1.receiver_id) = t2.receiver_id AND
                               t1.id = t2.max_id
                            WHERE t1.sender_id = ? OR t1.receiver_id = ?) result
                INNER JOIN users s ON s.id = result.sender_id
                INNER JOIN users r ON r.id = result.receiver_id
                ORDER BY result.sent_at DESC

这是字母模型:

/**
 * The user who wrote the letter
 *
 */
public function author()
{
    return $this->belongsTo(User::class, 'sender_id');
}

/**
 * The person who will receive the letter
 *
 */
public function recipient()
{
    return $this->belongsTo(User::class, 'receiver_id');
}

这是用户模型:

/**

* Get all the sent letters by this user
* /

public function letters_sent()
{
    return $this->hasMany(Letter::class, 'sender_id');
}

/**

* Get all the received letters by this user
* /

public function letters_received()
{
    return $this->hasMany(Letter::class, 'receiver_id');
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题