【问题标题】:Appended one accessor but resource has more than one, how is this possible? - Laravel附加了一个访问器但资源有多个,这怎么可能? - 拉拉维尔
【发布时间】: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


【解决方案1】:

您可以使用 unset 删除属性 profile

public function getHasProfileAttribute()
{
    $exists = $this->profile;
    unset($this->profile);
    if($exists){
        return 1;
    }
    else{
        return 0;
    }
}

【讨论】:

  • 谢谢,unset() 有效,但我遇到了$this->unsetRelation($relation),它也有效。知道为什么会发生这种情况吗?
  • 有效吗?您可以参考链接的想法:[链接](stackoverflow.com/questions/52278128/…
  • 很抱歉将您的答案删除为正确答案,我发现了问题并更新了另一个解决方案。
  • @PremArumugam 没问题,如果你有更好的解决方案。
【解决方案2】:

您可以使用documentation 中的except() 方法

User::find(1)->get()->except('profile');

也许您必须更改订单,我现在无法测试,但这是个好主意

【讨论】:

  • 这会很困难,因为我必须在检索到我的用户模型的每个控制器上进行更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多