【问题标题】:access to belongsTo method in same model laravel访问同一模型 laravel 中的 belongsTo 方法
【发布时间】:2023-03-21 13:52:01
【问题描述】:

我使用这个模型但是使用这个模型显示以下错误:

Failed calling App\User::jsonSerialize()

但删除 "$this->customer->name" 结果是可以的。 谢谢ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss。

class User extends Authenticatable
{

    /**
     * Get the user's customer name.
     *
     * @param  string $value
     * @return array
     */
    public function getCustomerIdAttribute($value)
    {
        return [
            'id' => $value,
            'name' => $this->customer->name
        ];
    }

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'customer_id' => 'array',
    ];

    /**
     * Get the customer record associated with the user.
     */
    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }
}

【问题讨论】:

  • $user = Auth::user();返回 $user;

标签: laravel model eloquent foreign-keys


【解决方案1】:

您的问题是$this->customer 正在返回null,这导致$this->customer->name 导致错误。

当你json_encode一个Model,或者把它转换成一个字符串,或者在它上面调用toJson,它会调用jsonSerialize()方法。

在某些时候,这最终会调用您定义的 getCustomerIdAttribute() 访问器。在此访问器中,您有声明 $this->customer->name。但是,如果当前模型与客户记录无关,则$this->customer 将返回null,然后$this->customer->name 将导致错误。当$this->customer->name 导致错误时,它会导致jsonSerialize() 失败。

在您的访问器中,只需确保在尝试访问 name 属性之前检查 $this->customer 是否有效:

public function getCustomerIdAttribute($value)
{
    return [
        'id' => $value,
        'name' => ($this->customer ? $this->customer->name : null)
    ];
}

【讨论】:

  • 再次显示同样的错误。我想在所有选择的用户中显示客户名称。
  • @HassanDL 这应该可以解决您遇到的错误。如果您正在寻找有关如何做某事的不同帮助,则需要提出一个新问题,以指定您想要什么,并提供数据和输出示例,以及您迄今为止尝试过的内容。
  • 非常感谢您的回答。新问题:stackoverflow.com/questions/40327812/…
猜你喜欢
  • 2019-06-05
  • 2020-10-17
  • 1970-01-01
  • 2016-07-19
  • 2015-09-20
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多