我在口才模型上有以下内容:

public function setGameName(\Game $game)
{
    $this->gameName = $game->find($this->gameId)->name;
}


在使用dd()之前在模型上使用toArray()时,得到以下信息:

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
}


如您所见,gameNameattributesoriginal之外。如果此时在模型上运行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/

10-10 13:56