【发布时间】:2021-10-21 07:05:28
【问题描述】:
我正在尝试在模型上使用访问器来返回关系是否存在的状态。
我的用户模型:
class User {
protected $appends = ['has_profile'];
public function profile()
{
return $this->hasOne(Profile::class)
}
public function getHasProfileAttribute()
{
$exists = $this->profile;
if($exists){
return 1;
}
else{
return 0;
}
}
}
问题是当通过User::find(1)->get(); 加载用户模型时,profile 属性也被加载到 JSON 资源中,而我只希望我的 JSON 返回中的has_profile 属性。我应该如何在不加载关系的情况下查询关系存在,还是应该卸载关系?
我得到了什么
"data": {
"id": 270,
"name": "John Doe",
"mobile_number": "01234567890",
"created_at": "2021-08-19T06:55:33.000000Z",
"updated_at": "2021-08-19T06:55:33.000000Z",
"deleted_at": null,
"has_profile": 1,
"profile": {
"id": 1,
"details": "Details"
}
}
我想要什么
"data": {
"id": 270,
"name": "John Doe"
"mobile_number": "01234567890",
"created_at": "2021-08-19T06:55:33.000000Z",
"updated_at": "2021-08-19T06:55:33.000000Z",
"deleted_at": null,
"has_profile": 1
}
更新的解决方案
问题是$this->profile 导致附加配置文件关系。当用作$this->profile()->get(); 或$this->profile()->first(); 时,它的工作原理与预期一样。
【问题讨论】:
-
fyi,使用
->find()时不需要使用->get(),User::find(1);就可以了 -
has()方法总是返回 true,即使关系不存在。不知道为什么。例如:$exists = is_null($this->has('profile')->get())
标签: php json laravel eloquent laravel-8