我具有以下其中一项职能:
$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;
}
那么我该如何过滤那些已经在上面的控制器函数中过滤过的记录,并且在属性返回中什么也不返回?
答案 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对它的工作原理进行了很好的解释,因此无需复制其合法答案的内容
查询如下:
//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();