单个laravel查询中的多选查询

时间:2017-10-12 06:02:30

标签: laravel laravel-5 laravel-5.3

我想编写laravel查询qhich想要在单个查询中有多个选择查询

select name,owner from project where owner in (select a.user_name from users a left join users b on a.manager=b.firstname where a.user_name='sridhar.ps' or a.manager like '%sridhar p%' or b.manager like '%sridhar p%') and customer_code='OTH_0071'

上面的查询列出了我想要的内容。我想在laravel中更改查询

2 个答案:

答案 0 :(得分:1)

在whereRaw的帮助下你可以这样做

DB::table('project')->where('customer_code','OTH_0071')->whereRaw("owner in (select a.user_name from users a left join users b on a.manager=b.firstname where a.user_name='sridhar.ps' or a.manager like '%sridhar p%' or b.manager like '%sridhar p%')")->select('name','owner')->get();

使用变量

DB::table('project')->where('customer_code','OTH_0071')->whereRaw("owner in (select a.user_name from users a left join users b on a.manager=b.firstname where a.user_name='sridhar.ps' or a.manager like '%".$manager."%' or b.manager like '%sridhar p%')")->select('name','owner')->get();

了解更多信息vist laravel $ manager

希望它会对你有所帮助!

答案 1 :(得分:1)

我可能会首先使用一系列连接重写您的查询:

SELECT
    p.name,
    p.owner
FROM project p
INNER JOIN
(
    SELECT a.user_name
    FROM users a
    LEFT JOIN users b
        ON a.manager = b.firstname
    WHERE
        a.user_name = 'sridhar.ps'   OR
        a.manager LIKE '%sridhar p%' OR
        b.manager LIKE '%sridhar p%'
) t
    ON p.owner = t.user_name
WHERE
    p.customer_code = 'OTH_0071';

然后使用原始子查询构建Laravel查询,以表示上面显示为t的表:

$subquery  = "(SELECT a.user_name FROM users a LEFT JOIN users b ";
$subquery .= "ON a.manager = b.firstname ";
$subquery .= "WHERE a.user_name = 'sridhar.ps' OR a.manager LIKE '%sridhar p%' ";
$subquery .= "OR b.manager LIKE '%sridhar p%') AS t";
DB:table('project)
    ->select('name', 'owner')
    ->join(DB::raw($subquery), 'p.owner', '=', 't.user_name')
    ->where('customer_code','OTH_0071')
    ->get();

这种连接方法可能比您目前拥有的方式更高效。在任何情况下,你都可以测试这个答案,将它与@Gaurav的答案进行比较,然后使用最好的答案。