[英]Nested SQL Query in Laravel Controller
我在控制器中運行了兩個查詢。 我需要將第一個查詢的值傳遞到第二個查詢。 我希望將這兩個查詢的結果發送到我的視圖。
public function jobs()
{
$query = DB::table("dbQuotes")
->leftJoin("dbACT", "dbQuotes.act_id", "=", "dbACT.ID")
->leftJoin("dbOpps", "dbQuotes.act_id", "=", "dbOpps.contactID")
->leftjoin('dbBids', 'dbQuotes.act_id','=',
DB::raw('dbBids.quote_id AND dbBids.user_id = '. Auth::user()->id))
->where("dbQuotes.active", "=", "1")
->select("dbQuotes.*", "dbACT.*", "dbBids.*",
(DB::raw('date_format(dbQuotes.posted_date, "%d/%m/%Y %H:%i") as posted_date')),
(DB::raw('date_format(dbOpps.expected_date, "%d/%m/%Y") as expected_date')))
->groupBy("dbQuotes.id")
->orderBy("posted_date", "desc")
->get();
$passinvaluehere = $query->dbQuotes.act_id
$bids = DB::table("dbBids")
->where("quote_id", "=", $passinvaluehere)
->get();
return view('jobs', ['query' => $query,'bids' => $bids]);
}
如果我將傳遞的值替換為數字,即“ 8763”,則我的查詢有效,並以正確的方式建立了視圖。 我的問題是,如何在此函數中將dbQuotes.act_id的值傳遞給第二個查詢?
***答案中的更新代碼:[錯誤調用非對象上的成員函數lists()]
public function jobs()
{
$query = DB::table("dbQuotes")
->leftJoin("dbACT", "dbQuotes.act_id", "=", "dbACT.ID")
->leftJoin("dbOpps", "dbQuotes.act_id", "=", "dbOpps.contactID")
->leftJoin('dbBids', 'dbQuotes.act_id','=',
DB::raw('dbBids.quote_id AND dbBids.user_id = '. Auth::user()->id))
->where("dbQuotes.active", "=", "1")
->select("dbQuotes.*", "dbACT.*", "dbBids.*",
(DB::raw('date_format(dbQuotes.posted_date, "%d/%m/%Y %H:%i") as posted_date')),
(DB::raw('date_format(dbOpps.expected_date, "%d/%m/%Y") as expected_date')))
->groupBy("dbQuotes.id")
->orderBy("posted_date", "desc")
->get();
$act_id = $query->lists('act_id');
$bids = DB::table("dbBids")
->whereIn("quote_id", $act_id)
->get();
return view('jobs', ['query' => $query,'bids' => $bids]);
}
如果您有多個記錄(按照->get()
方法),則有兩種方法:要么遍歷Collection並在每次迭代中進行查詢(錯誤),要么創建一個ID數組並在第二個中使用whereIn
查詢(更好):
$passinvaluehere = $query->lists('act_id');
// https://laravel.com/docs/5.2/queries#retrieving-results
// this creates and array of `act_id` s
$bids = DB::table("dbBids")
->whereIn("quote_id", $passinvaluehere)
->get();
// you now have a Collection of multiple $bids
如果您只希望從第一個查詢中獲得一條記錄,則需要使用first()
來更改fetcher方法,或者僅獲取實際集合的第一個元素,例如first($query)
或$query[0]
$query = DB::table("dbQuotes")
....
->first();
$passedvaluehere = $query->act_id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.