【问题标题】:Return collection where attribute of model records is empty in Laravel返回 Laravel 中模型记录属性为空的集合
【发布时间】:2023-04-03 18:45:01
【问题描述】:

我的一项职能有以下部分:

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

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

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

那么我将如何过滤那些已经在上述控制器函数中过滤的记录在属性返回中也不返回任何内容?

【问题讨论】:

  • 我有点不知所措,马修,为什么你坚持在你的帖子上签名,并添加聊天材料。我至少七次告诉你我们这里的首选风格。你可以清楚地阅读英语,而且你显然不傻。我倾向于将蔑视或恶意归咎于你的性格,但我更希望你只是积极地与社区互动,这样我才能更好地考虑你。您需要我们的指南的元参考吗?

标签: laravel laravel-5 eloquent


【解决方案1】:

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

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

subQuery 与您在函数中使用的 ->where()s 基本相同,但在 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();

【讨论】:

  • 嗨蒂姆 - 我已经提到我需要它来返回那些没有属性的人,我所要做的就是将 whereHas 更改为 whereDoesntHave?
  • 哦,是的,对不起。如果要查询该子查询是否存在,则使用->whereHas(),否则使用->whereDoesntHave()
【解决方案2】:

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

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();

【讨论】:

  • 这在我的回答中已在 cmets 中确立。
猜你喜欢
  • 2021-08-16
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多