为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel:使用 belongsTo() 向我的模型添加意外属性

Laravel:使用 belongsTo() 向我的模型添加意外属性

PHP
梦里花落0921 2023-03-04 17:51:53
我正在使用 Lumen 编写 REST API。我的示例有 2 个模型User和Post. Postmodel 使用该方法belongsTo获取User创建此帖子的模型。我的目标是定义一个访问器,这样我就可以像那样获取帖子的作者用户名Post::find($id)->author。所以根据文档我这样做:后.php:<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Post extends Model{  protected $table = 'posts';  protected $appends = ['author'];  protected $fillable = [    'title',    'description'  ];  protected $hidden = [    'user_id',    'created_at',    'updated_at'  ];  public function user()  {    return $this->belongsTo('App\User', 'user_id');  }  public function getAuthorAttribute()  {    return $this->user->username;  }}现在 getter 工作得很好,我可以很容易地得到给定的作者Post。Post但是,如果我尝试在 JSON 响应中返回,它也会向我返回奇怪的属性user,这些属性似乎来自我user()调用 a 的方法belongsTo():return response()->json(Post::find(2), 200);{    "id": 2,    "title": "Amazing Post",    "description": "Nice post",    "author": "FooBar",    "user": {        "id": 4,        "username": "FooBar"    }}如果我使用它,attributesToArray()它会按预期工作:return response()->json(Post::find(2)->attributesToArray(), 200);{    "id": 2,    "title": "Amazing Post",    "description": "Nice post",    "author": "FooBar"}此外,如果我删除 gettergetAuthorAttribute()和$appends声明,我不会得到意外的user属性。但是我不想每次都使用这个方法,如果我想返回我所有的Post使用,它不会让它工作:return response()->json(Post::all(), 200);有人知道为什么我使用这个附加属性belongsTo吗?
查看完整描述

2 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

此行为是由于性能。当你$post->user第一次调用时,Laravel 会从数据库中读取并保存$post->relation[]以备下次使用。所以下次 Laravel 可以从数组中读取它并防止再次执行查询(如果你在多个地方使用它会很有用)。


另外,用户也是一个属性,当你调用或时,Laravel 合并 $attributes并$relations排列在一起$model->toJson()$model->toArray()


Laravel 的模型源代码:


public function toArray()

{

    return array_merge($this->attributesToArray(), $this->relationsToArray());

}


public function jsonSerialize()

{

    return $this->toArray();

}


查看完整回答
反对 回复 2023-03-04
?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

您的第一种方法很好,您只需要将“用户”添加到 $hidden 数组中


<?php

namespace App;


use Illuminate\Database\Eloquent\Model;


class Post extends Model

{

  protected $table = 'posts';

  protected $appends = ['author'];


  protected $fillable = [

    'title',

    'description'

  ];


  protected $hidden = [

    'user_id',

    'created_at',

    'updated_at',

    'user', // <-- add 'user' here

  ];


  public function user()

  {

    return $this->belongsTo('App\User', 'user_id');

  }


  public function getAuthorAttribute()

  {

    return $this->user->username;

  }

}

您得到的模型将是:


{

  "id": 2,

  "title": "Amazing Post",

  "description": "Nice post",

  "author": "FooBar"

}


查看完整回答
反对 回复 2023-03-04
  • 2 回答
  • 0 关注
  • 196 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信