在Laravel中模型记录的属性为空的返回集合

时间:2018-07-20 18:31:42

标签: laravel laravel-5 eloquent

我具有以下其中一项职能:

$shipmentsNotSent = DB::table('shipments')
        ->whereNull(['billedAt','agentBilling'])
        ->whereBetween('date', [$startDateNS, $nowNS])
        ->get();

这很好用,但是我目前正在简化模型/控制器和各种其他文件,并且我还需要它只返回在我设置的自定义属性中不返回任何内容的记录(见下文)。运输模型。

public function getbillingUploadStatusAttribute(){
    $billingUploadStatus = $this->billingUpdates()->where([
        ['actionCategoryID', 1],
        ['actionID', 2]
    ])->orderBy('created_at','desc')->first();
    return $billingUploadStatus;
}

那么我该如何过滤那些已经在上面的控制器函数中过滤过的记录,并且在属性返回中什么也不返回?

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找->whereHas()

->whereHas("billingUpdates", function($subQuery){
    $subQuery->where("actionCategoryID", "=", 1)->where("actionID", "=", 2);
});

subQuery必将执行与在函数中使用的相同的->where(),但是在whereHas上下文中使用时,会将父模型记录约束为那些匹配。

注意:这不能与DB::table("shipments")一起使用,而是需要在关联的模型上使用(我假设是Shipment)。完整的查询如下所示:

$shipmentsNotSent = Shipment::whereHas("billingUpdates", function($subQuery){
    $subQuery->where("actionCategoryID", "=", 1)->where("actionID", "=", 2);
})->whereNull("billedAt")
->whereNull("agentBilling"])
->whereBetween('date', [$startDateNS, $nowNS])
->get();

编辑:如果要查询此功能的不存在,请使用->whereDoesntHave()

$shipmentsNotSent = Shipment::whereDoesntHave("billingUpdates", function($subQuery){
    $subQuery->where("actionCategoryID", "=", 1)->where("actionID", "=", 2);
})->whereNull("billedAt")
->whereNull("agentBilling"])
->whereBetween('date', [$startDateNS, $nowNS])
->get();

答案 1 :(得分:0)

我相信您正在寻找这个,这与@Tim Lewis提到的whereHas相反。 Lewis对它的工作原理进行了很好的解释,因此无需复制其合法答案的内容

  

https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_whereDoesntHave

查询如下:

//Assuming Shipments is your Eloquent Model
Shipments::whereDoesntHave("billingUpdates", function($advancedWhereDoesntHave){
    $advancedWhereDoesntHave->where("actionCategoryID", "=", 1)->where("actionID", "=", 2);
})->whereNull(['billedAt','agentBilling'])
  ->whereBetween('date', [$startDateNS, $nowNS])
  ->get();