我在 Eloquent 模型上有以下内容:
public function setGameName(\Game $game)
{
$this->gameName = $game->find($this->gameId)->name;
}
当我在使用 toArray()
之前在模型上使用 dd()
时,我得到以下结果:
Promotion {#251 ▼
#table: "Promotion"
#primaryKey: "promotionId"
#guarded: array:1 [▶]
#game: null
+gameName: "3Peaks"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:14 [▶]
#original: array:14 [▶]
#relations: array:5 [▶]
#hidden: []
#visible: []
#appends: []
#fillable: []
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
如您所见,gameName
位于 attributes
和 original
之外。如果我此时在模型上运行 toArray()
,则返回的数组没有我需要的 gameName
属性。如有任何帮助,我们将不胜感激。
最佳答案
将其设置在$this->attributes
上,蛇形:
public function setGameName(\Game $game)
{
$this->attributes['game_name'] = $game->find($this->gameId)->name;
}
关于php - 如何将对象属性添加到对象的属性中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144860/