php - Laravel 根据关系结果返回数据
问题描述
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.php
function 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
因为代理数组是空的。我怎样才能做到这一点?
解决方案
试试这个 :
$customers = $query->orderBy('id', 'desc')->whereDoesntHave('agents')->get();
如果你想得到没有代理的客户。在这里阅读更多
推荐阅读
- python - 如何在 python 中使用十六进制值而不是 RGB 值。蟒蛇 2.7
- docker - 从前端容器到后端容器的请求
- javascript - 点对点 Javascript 和其他东西
- javascript - 使用函数 onclick 时出现语法错误
- php - Symfony 仅在集合的第一行呈现表单
- node.js - Node Express“favicon.ico”未找到错误
- magento - Magento 1.9.3.9 上的万事达卡支付网关服务
- python - 数据库问题 sqlite3.Flask 操作错误
- r - 从 R 中的人口统计包创建 demogdata
- c# - Xamarin.Android 和用户可下载的可执行代码 (.dll)