簡體   English   中英

在Laravel Query Builder或SQL中將兩個查詢合並為一個

[英]Combine two queries into one in Laravel Query Builder or SQL

SQL查詢不是我的強項之一,我遇到了一個我可以解決的問題,但我希望它可以改善並提高效率。 我在這些示例中使用Laravel的查詢生成器,但如果需要的話,我不介意使用原始請求。

目前,我正在進行以下兩個查詢,然后將它們合並。

 $acc_id = 10;
 $locat_id= 3;  

//First get all sites with account id
$allSites = collect(DB::table('sites')->where('acc_id', $acc_id)->get()):

//Next get only sites with account id and connections with current location id
$connectedSites = collect( 
    DB::table('sites')
        ->select('sites.id','name','active','url')
        ->join('connections as conn','sites.id','=','conn.site_id')
        ->where('acc_id',$acc_id)
        ->where('conn.locat_id',$locat_id)
        ->get()
);

//Merge the collections and drop first row with duplicate site_id
$sites = $allSites->merge($connectedSites)->keyBy('id');

return $sites;

所以這給了我想要的結果。 例如,與該帳戶ID關聯的所有站點,以及與該帳戶和位置ID關聯的站點的連接數據。 但是,我想學習如何在一個查詢中做到這一點。

嘗試左聯接:

$sites = DB::table('sites')
    ->select('sites.*','name','active','url')
    ->leftJoin('connections as conn', function($query) use($locat_id) {
        $query->on('sites.id', '=', 'conn.site_id')
            ->where('conn.locat_id', $locat_id);
    })
    ->where('acc_id',$acc_id)
    ->get();

可以用一個查詢來完成,但是我用雄辯的方法代替了查詢生成器。 查看with()方法,它使您可以渴望加載關系。

$sites = Sites::with('connections')->where('acc_id', $acc_id)->get();

現在,您可以從模型實例訪問連接數據,而無需執行任何查詢。

foreach($sites as $site){
    $site->connection->stuff; // No query generated
}

如果您需要將兩者分開也很容易。

$connectedSites = $sites->where('connection.locat_id', $locat_id)
// No query generated from the above, but now $connectedSites has all of
// the connected sites

當您進入laravel的集合時,您會發現可以使用它們來替換很多查詢。

https://laravel.com/docs/5.6/collections#available-methods

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM