如何始终将属性附加到 Laravel Eloquent 模型?

新手上路,请多包涵

我想知道如何始终将一些数据附加到 Eloquent 模型而不需要询问它,例如在获取 Posts 表单数据库时我想将每个用户的用户信息附加为:

 {
    id: 1
    title: "My Post Title"
    body: "Some text"
    created_at: "2-28-2016"
    user:{
            id: 1,
            name: "john smith",
            email: "example@mail.com"
         }
}

原文由 Mustafa Dwekat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 367
2 个回答

经过一番搜索,我发现您只需将所需的属性添加到 Eloquent 模型中的 $appends 数组中:

  protected $appends = ['user'];

更新: 如果该属性存在于数据库中,您可以使用 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: "example@mail.com"
         }
}

原文由 Mustafa Dwekat 发布,翻译遵循 CC BY-SA 3.0 许可协议

您的数据库表不正确,您不需要附加任何可以使用关系加载的内容:

首先,您的帖子表应该有 user_id 列,它引用您的用户表 id 列:{ id: 1 user_id: 1 title: “My Post Title” body: “Some text” created_at: “2-28-2016” }

然后在您的帖子模型中,您必须根据您的 user_id 定义关系:

 public function user() {
    return $this->belongsTo("App\Models\User", "user_id");
}

然后在您的 get api 调用中,您所要做的就是使用以下方法加载此关系:例如 Posts::with(“user”)->get();

原文由 Taha Malik 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题