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();
}

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"
}
- 2 回答
- 0 關注
- 303 瀏覽
添加回答
舉報