可选的Laravel

时间:2018-02-10 21:57:27

标签: php laravel

鉴于我有一个简单的连接查询:

$googleAds = TrackingApi::where("company_id",$companyId)
                         ->leftJoin("googleads",function($join) use ($date){

                       $join->on("tracking_api.google_id", "googleads.id")
                            ->where("googleads.created", "<=", $date
                            })
                         ->select(DB::raw('count(googleads.id) as totalAds'))->get();

从管理仪表板发出的数据参数,但是它的可选参数。

问题:如果$date没有给出,我该怎么办?

澄清:$date没有给出时,只是正常执行查询。

3 个答案:

答案 0 :(得分:1)

您可以使用when方法:

$googleAds = TrackingApi::where("company_id",$companyId)
     ->leftJoin("googleads",function($join) use ($date){
         $join->on("tracking_api.google_id", "googleads.id")
              ->when($date, function ($query) use ($date) {
                  return $query->where("googleads.created", "<=", $date
              })
     })
     ->select(DB::raw('count(googleads.id) as totalAds'))->get();

答案 1 :(得分:0)

作为替代方案:

$googleAds = TrackingApi::where("company_id", $companyId)
     ->leftJoin("googleads",function($join) use ($date){    
         $join->on("tracking_api.google_id", "=", "googleads.id");
         if (!empty($date)) 
            $join->where("googleads.created", "<=", $date);
      });                
     ->select(DB::raw('count(googleads.id) as totalAds'))
     ->get();

答案 2 :(得分:0)

@ user320487的答案是正确的,但是,您也可以在方法中传递第二个参数,而不是在闭包器中使用“ use”关键字,因为这将是更具可读性和可维护性的代码。

$googleAds =
    TrackingApi::whereCompany_id($companyId)
        ->leftJoin("googleads", function ($join) use ($date) {
            $join->on("tracking_api.google_id", "googleads.id")
                ->when($date, function ($query, $date) {
                    return $query->where("googleads.created", "<=", $date);
                });
        })
        ->select(DB::raw('count(googleads.id) as totalAds'))
        ->get();
相关问题