亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 303 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號