2016-02-29 185 views

回答

4

一些搜索后我发现,你只需要你想的属性添加到$appends阵列在你的口才型号:

protected $appends = ['user']; 

更新:如果在数据库中存在的属性,你可以只我们根据下面

David Barker's建议E protected $with= ['user'];然后创建一个访问为:

public function getUserAttribute() 
{ 

    return $this->user(); 

} 

这样,你总是将有可作为每个岗位的用户对象:

{ 
    id: 1 
    title: "My Post Title" 
    body: "Some text" 
    created_at: "2-28-2016" 
    user:{ 
      id: 1, 
      name: "john smith", 
      email: "[email protected]" 
     } 
} 
+2

你的使用情况有点奇怪,因为与'User'的关系会使'$ model-> user'可用于您而无需使用append。另外,当模型转换为JSON或转换为数组时,如果您已加载该关系,则“user”键将存在。如果您始终希望用户将'protected $ with = ['user'];'添加到模型中。 –

+0

是的,正确的方式我总是要使用'$ model-> user',但我需要有用户对象,而无需手动要求它另外我不想通过一个循环,我使用它在API中,所以当我显示文章列表时,我无法获得这些内容。这样用户对象将始终自动为您提供。 –

+3

不,当你添加'protected $ with = ['user']'时,它会在你获得模型时自动加载。追加适用于您希望模型中的数据库中不可用的数据。 –

相关问题