为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 根据关系结果返回数据

Laravel 根据关系结果返回数据

PHP
狐的传说 2022-06-17 14:28:36
PostController.php$customers = $query->orderBy('id', 'desc')->with('agents:agents.id')->get();        foreach ($customers as $customer) {            $customer->calculator = $this->calculator($customer);        }        return response()->json($customers, 200 );Post.phpfunction agents()    {        return $this->belongsToMany('App\Agent','files','post_id','agent_id');    }这将返回正确的数据,如下所示:[{    "id": 5,    "hash": "SqB29tkfm1dwGsXp4ZCV",    "agents": [{      "id": 1,      "pivot": {        "post_id": 5,        "agent_id": 1      }    }]  },  {    "id": 4,    "hash": "SqH29tkfm1dwGsXp4ZCV",    "agents": []  },  {    "id": 3,    "hash": "RqH29tkfm1dwGsXp4ZCV",    "agents": [{      "id": 1,      "pivot": {        "post_id": 3,        "agent_id": 1      }    }]  },  {    "id": 1,    "hash": "RqH29tkfm1dwGrXp4ZCV",    "agents": [{      "id": 1,      "pivot": {        "post_id": 1,        "agent_id": 1      }    }]  }]但我想要的是只返回那些有空代理的数据[],在这种情况下,应该只返回 id4因为代理数组是空的。我怎样才能做到这一点?
查看完整描述

2 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

尝试这个 :

$customers = $query->orderBy('id', 'desc')->whereDoesntHave('agents')->get();

如果你想得到没有代理的客户。在这里阅读更多


查看完整回答
反对 回复 2022-06-17
?
临摹微笑

TA贡献1982条经验 获得超2个赞

你可以同时使用 dontHave 或 whereDoesntHave like

$customers = $query->orderBy('id', 'desc')->doesntHave('agents')->get();

或者

$customers = $query->orderBy('id', 'desc')->whereDoesntHave('agents')->get();


查看完整回答
反对 回复 2022-06-17
  • 2 回答
  • 0 关注
  • 162 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号