复杂的INNER JOIN来自Laravel中的3个表的Mysql查询

时间:2016-03-18 07:01:42

标签: php mysql laravel laravel-5 inner-join

我已经在这几个小时没有解决方案了。我想到了laravel关系,但不知道如何传递第二个条件,因为我需要与3个表相关联。我想在laravel中使用下面的查询。

SELECT
subscriptions.subscribed_to,
broadcasts. *,
FROM subscriptions
INNER JOIN broadcasts
WHERE subscriptions.subscriber = {$user_id}
AND (
    SELECT COUNT(*) FROM seen_broadcasts
    WHERE user_id = {$user_id}
    AND broadcast_id = broadcasts.id
) = 0
ORDER BY  broadcast.date DESC

有3张桌子。

  1. 订阅:subscriber_id 订阅 broadcaster_id。
  2. 广播:保存广播公司的消息。
  3. seen_broadcast :订阅者在阅读广播时保存的信息。这有助于我们向广播公司提供详细的统计数据。 user_id = subscriber_user_id, broadcast_id = broadcast_message_id
  4. 我希望能够从用户已订阅但未见过的所有广播公司获得广播。

    上面的查询目前在laravel之外。

1 个答案:

答案 0 :(得分:1)

经过多次解决后,我最终得到了这个:

$broadcast_result = DB::select( DB::raw("
                                        SELECT
                                        subscriptions.subscribed_to,
                                        broadcasts.*
                                        FROM subscriptions
                                        INNER JOIN broadcasts
                                        WHERE subscriptions.browser_agent_id = :subsc_id
                                        AND broadcasts.user_id = subscriptions.subscribed_to
                                        AND (
                                            SELECT COUNT(*) FROM broadcasts_seen
                                            WHERE broadcast_id = broadcasts.id
                                            AND subscriber_id = subscriptions.subscriber_id
                                        ) = 0
                                        ORDER BY  broadcasts.date DESC LIMIT 1
                                    "), array(
                                       'subsc_id' => $subscriber->id
                                     ));
$broadcast_set = $broadcast_result[0];

还在控制器中添加use DB;

如果有更好的方法,请分享。