2017-07-17 59 views
1

下面是我的SQL語法,如何實現它在laravel,在此先感謝。如何形成以下MySQL查詢laravel查詢語法?

SELECT * FROM `tr_policy_privacy` AS pri 
LEFT JOIN 
(SELECT * FROM tr_policy_full_create as cri WHERE cri.client_id=156 and cri.policy_type_id = 1) 
AS hours 
ON pri.id = hours.policy_template_edit 

到目前爲止,我已經嘗試過這一點,但我試圖找到一種方式使用左連接內的函數。

DB::table('tr_policy_privacy AS pri') 
    ->select(['cri.policy_title', 'cri.policy_type', 'cri.policy_std', 'cri.policy_version', 'cri.approved_user_id', 'cri.effective_date', 'cri.last_revised_date', 'cri.id']) 
    ->leftJoin(
     DB::raw('(
     SELECT * FROM tr_policy_full_create as pol WHERE pol.client_id=156 and pol.policy_type_id = 1 
     ) AS cri'),'pri.id', '=', 'cri.policy_template_edit' 
    ) 
    ->get(); 
+4

你有什麼到目前爲止類的頂部? – Tajgeer

+0

你可以試試嗎?請嘗試搜索類似的主題[如](https://laravel.com/docs/5.4/queries)。 –

+0

在stackoverflow中有很多類似的問題。 –

回答

0
public function show($slug) 
{ 
    $query = DB::table('wn_entries') 
    ->leftJoin('wn_criteria', 'wn_entries.id', '=', 'wn_criteria.entry_id') 
    ->leftJoin('wn_attachment_entries', 'wn_entries.id', '=', 'wn_attachment_entries.entry_id') 
    ->leftJoin('wn_team', 'wn_entries.id', '=', 'wn_team.entry_id') 
    ->leftJoin('wn_confirmation', 'wn_entries.id', '=', 'wn_confirmation.entry_id') 
    ->leftJoin('wn_users', 'wn_entries.user_id', '=', 'wn_users.id') 


    ->select(
     'wn_entries.*', 
     'wn_entries.id as main_entry_id', 
     'wn_criteria.id as criteria_entry_id', 
     'wn_criteria.*', 
     'wn_attachment_entries.id as attachment_entry_id', 
     'wn_attachment_entries.*', 
     'wn_team.id as team_entry_id', 
     'wn_team.*', 
     'wn_confirmation.id as confirmation_entry_id', 
     'wn_confirmation.*', 
     'wn_users.*' 
     ); 


    $query = $query->where('wn_entries.slug',$slug); 


     $entrydata = $query->get()->toArray(); 
    $entries = $entrydata['0']; 
    return view('entries.show', compact('entries')); 

} 

你從這段代碼的想法。

+0

不,我沒有任何想法。 – Crysis

+0

$ query = DB :: table('table_1') - > leftJoin('table_2','table_1.id','=','table_2.id') - > select( 'table_1。*', 'TABLE_2 *' ); $查詢= $查詢 - >其中( 'table_1.name', 'abc_name'); $ entrydata = $查詢 - >的get() - >指定者(); –

+0

請檢查它。以這種方式創建的laravel連接查詢 –

1

如果您的原始SQL是正確的,那麼儘量在laravel

$sql = " 
SELECT * FROM `tr_policy_privacy` AS pri 
LEFT JOIN 
(SELECT * FROM tr_policy_full_create as cri WHERE cri.client_id=156 and cri.policy_type_id = 1) 
AS hours 
ON pri.id = hours.policy_template_edit"; 

$result = DB::select($sql); 

使用DB命名空間直接執行到

use DB; 
+0

感謝您的答覆,但我'試圖找到利用函數內部左側加入的方式。 – Crysis