Laravel 控制器中的嵌套 SQL 查询


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() 方法),则有两种方法:要么遍历集合并在每次迭代中进行查询(错误),要么创建一个 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

如果您只希望第一个查询中只有一条记录,则需要更改 fetcher 方法,改用 first(),或者只获取实际集合的第一个元素,例如 first($query)$query[0]

$query = DB::table("dbQuotes")
         ....
         ->first();
$passedvaluehere = $query->act_id;