2017-10-12 143 views
1

我想寫qhich希望將laravel查詢在單個查詢多個選擇查詢多個選擇查詢

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' 

上面的查詢列表我想要exactly.I的outpu想改變查詢在laravel

回答

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 $經理

希望它會幫助你的!

+0

如何使用查詢$經理=「斯里達爾P」變量 – user3386779

+0

檢查現在編輯原始查詢解決方案 –

+0

我想用變量 – user3386779

1

我可能會使用一系列的連接第一重寫查詢:

$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(); 

此連接:

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'; 

使用原始子查詢,以表示該表別名爲t上面然後建立Laravel查詢方法可能比您目前擁有的更高性能。無論如何,你可以測試這個答案,將它與@Gaurav的答案進行比較,然後使用最好的方法。

+0

在哪裏添加客戶代碼 – user3386779

+0

@ user3386779對不起,我忽略了這一點。我更新了我的答案。就像平常那樣打電話給'where';你不需要原始查詢。 –

+0

我試圖選擇名稱和代碼,但不工作 – user3386779