php - 如何将对象属性添加到对象的属性中?

标签 php mysql laravel model eloquent

我在 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 位于 attributesoriginal 之外。如果我此时在模型上运行 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/

相关文章:

javascript - 将 POST 更改为 GET。现在 Ajax 返回多个帖子

php - xpath 中的 GET 语法

php - 将 MySQL 变量保存在 PHP $_SESSION 变量中

php - 没有 Laravel 的 Eloquent ORM 中的两个数据库

php - 如何根据时间戳在mysql中获取下一条/上一条记录

PHP - 发送 gzip 压缩的 JS/CSS

mysql - 使用 mysql in 使用 group_concat() 仅显示寄存器中存在的值

具有关系的MySQL过滤器查询

php - = .. PHP Laravel 之后的 > 运算符

php - Paypal PHP SDK批量支付