具有关系的Laravel 5.4访问器返回相关模型

时间:2017-02-25 15:20:27

标签: relationship accessor laravel-5.4 laravel-eloquent

我可能错过了一些非常明显的东西,但到目前为止还没有运气。我有两个相关的模型,消息和用户。我试图只附加用户名'检索所有邮件时创建邮件的用户。然而,我正在获得完全序列化的相关用户模型。我知道我可以隐藏在我的用户模型中,但我想避免这种情况。

在我的消息模型中,我创建了一种关系

public function createdBy()
{
    return $this->belongsTo('App\User', 'created_by');
}

然后我添加了

protected $appends = ['username'];

连同自定义属性

public function getUsernameAttribute($value)
{
    $username = null;
    if ($this->createdBy){
        $username = $this->createdBy->username;
    }
    return $username;
}

当我通过其他关系获取消息时,例如

return $channel->messages()->orderBy('id','desc')->get();

我最终得到以下回复:

  

[{" id":97," to_id":" 12345"," message":"这是消息内容"," created_at":" 2017-02-25 08:58:22"," created_by":{" id&#34 ;:1,"电子邮件":"删节""名称":"删节""用户名":& #34; myusername"," created_at":" 2016-09-26 16:00:00"," created_by":null," updated_at":" 2017-02-20 00:33:06"," updated_by":null}," updated_at":" 2017- 02-25 08:58:22"," updated_by":null," deleted_at":null," username":" myusername&#34 ;},...

我做错了什么,或者有更好的方法来完成我想要做的事情?

1 个答案:

答案 0 :(得分:2)

I didn't realize I was able to hide the relationship in the original model. I ended up hiding the createdBy relationship in the Messages model.

protected $hidden = [
   'createdBy'
];