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

我正在使用 Lumen 编写 REST API。我的示例有 2 个模型User和Post. Postmodel 使用该方法belongsTo获取User创建此帖子的模型。我的目标是定义一个访问器,这样我就可以像那样获取帖子的作者用户名Post::find($id)->author。所以根据文档我这样做:


后.php:


<?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'

  ];


  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吗?


梦里花落0921
浏览 204回答 2
2回答

侃侃无极

此行为是由于性能。当你$post->user第一次调用时,Laravel 会从数据库中读取并保存$post->relation[]以备下次使用。所以下次 Laravel 可以从数组中读取它并防止再次执行查询(如果你在多个地方使用它会很有用)。另外,用户也是一个属性,当你调用或时,Laravel 合并 $attributes并$relations排列在一起$model->toJson()$model->toArray()Laravel 的模型源代码:public function toArray(){&nbsp; &nbsp; return array_merge($this->attributesToArray(), $this->relationsToArray());}public function jsonSerialize(){&nbsp; &nbsp; return $this->toArray();}

慕婉清6462132

您的第一种方法很好,您只需要将“用户”添加到 $hidden 数组中<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Post extends Model{&nbsp; protected $table = 'posts';&nbsp; protected $appends = ['author'];&nbsp; protected $fillable = [&nbsp; &nbsp; 'title',&nbsp; &nbsp; 'description'&nbsp; ];&nbsp; protected $hidden = [&nbsp; &nbsp; 'user_id',&nbsp; &nbsp; 'created_at',&nbsp; &nbsp; 'updated_at',&nbsp; &nbsp; 'user', // <-- add 'user' here&nbsp; ];&nbsp; public function user()&nbsp; {&nbsp; &nbsp; return $this->belongsTo('App\User', 'user_id');&nbsp; }&nbsp; public function getAuthorAttribute()&nbsp; {&nbsp; &nbsp; return $this->user->username;&nbsp; }}您得到的模型将是:{&nbsp; "id": 2,&nbsp; "title": "Amazing Post",&nbsp; "description": "Nice post",&nbsp; "author": "FooBar"}
打开App,查看更多内容
随时随地看视频慕课网APP