Laravel的数据库查询生成器

时间:2019-06-11 15:26:33

标签: mysql laravel

我正在尝试使用Laravel的数据库查询生成器编写MySQL选择查询

我有这个mysql查询:

 SELECT * FROM `tweets` WHERE `user_id` = 1 OR `user_id` in (SELECT `follows_id` from `follows` where `user_id` = 1)

我正在尝试为Laravel编写它

$users = DB::table('tweets')
         ->where('user_id', '=', 1)

这怎么办?

3 个答案:

答案 0 :(得分:2)

即使看起来很丑,您也可以这样做。

$tweets = DB::table('tweets')
         ->where('user_id', 1)
         ->orWhereIn('user_id', DB::table('follows')->select('follows_id')->where('user_id', 1)->pluck('follows_id'))
         ->get();

答案 1 :(得分:1)

我建议进行SQL重写,因为ORIN(SELECT ...)的优化效果很差。
SQL结果可能是错误的,因为您没有提供示例数据,请参见Why should I provide a Minimal Reproducible Example for a very simple SQL query?来提供示例数据。

SELECT
  tweets.*
FROM
  tweets
WHERE
 tweets.user_id = 1

UNION ALL

SELECT
  tweets.*
FROM
 tweets
INNER JOIN
 follows ON tweets.user_id = follows.follows_id
WHERE
 follows.user_id = 1

我相信下面的Laraval代码可以做到这一点。但不确定,因为我有一段时间没有在Laraval编程了。

<?php
 $first = DB::table('tweets')
            ->select('tweets.*')
            ->where('user_id', '=', 1); 

 $second = DB::table('tweets')
             ->select('tweets.*')

             ->join('follows', 'tweets.user_id', '=', 'follows.follows_id')
             ->where('follows.user_id ', '=', 1)

            ->union($first)
            ->get();
?> 

答案 2 :(得分:-1)

不是答案;评论太久了...

这是对反向工程更简单的查询吗??

SELECT t.* 
  FROM tweets t  
  JOIN follows f
    ON f.follows_id = t.user_id 
 WHERE 1 IN (t.user_id,f.user_id);