繁体   English   中英

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()方法),则有两种方法:要么遍历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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM