Php 基于关系结果的拉威尔回归数据
PostController.phpPhp 基于关系结果的拉威尔回归数据,php,laravel,Php,Laravel,PostController.php $customers = $query->orderBy('id', 'desc')->with('agents:agents.id')->get(); foreach ($customers as $customer) { $customer->calculator = $this->calculator($customer); } return res
$customers = $query->orderBy('id', 'desc')->with('agents:agents.id')->get();
foreach ($customers as $customer) {
$customer->calculator = $this->calculator($customer);
}
return response()->json($customers, 200 );
function agents()
{
return $this->belongsToMany('App\Agent','files','post_id','agent_id');
}
Post.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 );
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();
如果你想得到没有代理的客户。
阅读更多信息,请尝试以下内容:
$customers = $query->orderBy('id', 'desc')->whereDoesntHave('agents')->get();
如果你想得到没有代理的客户。
更多信息请访问您可以同时使用doesntHave或whereDoesntHave
$customers = $query->orderBy('id', 'desc')->doesntHave('agents')->get();
或
您可以同时使用doesntHave或whereDoesntHave
$customers = $query->orderBy('id', 'desc')->doesntHave('agents')->get();
或
尝试类似于
->whereNull('agents')
?尝试类似于->whereNull('agents')
?