将新属性引入laravel集合对象

时间:2015-09-07 05:12:11

标签: php laravel eloquent

我需要在下面的laravel集合对象中引入一个新的字段/属性。正如你所看到的,我有像project,bidamount,awarddate等字段....我想添加另一个新字段'付费'对于集合中的每个项目。我怎么能这样做?

该集合是hasMany关系的结果。

Collection {#233 ▼
#items: array:20 [▼
0 => Project {#234 ▼
  #table: "projects"
  #attributes: array:11 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #original: array:11 [▼
    "id" => "15348"
    "project" => "Construction of blah blah blah"
    "bidamount" => "36830525"
    "awarddate" => "2012-08-15"
    "completedate" => "2013-12-31"
    "levyamount" => "55246"
    "fkcdb" => "1656"
    "fkfile" => "0"
    "fkclient" => "0"
    "created_at" => "0000-00-00 00:00:00"
    "updated_at" => "0000-00-00 00:00:00"
  ]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▶]
  #dates: []
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
}
1 => Project {#235 ▶}
2 => Project {#236 ▶}
3 => Project {#237 ▶}
4 => Project {#238 ▶}
5 => Project {#239 ▶}
6 => Project {#240 ▶}

1 个答案:

答案 0 :(得分:5)

如果您正在使用 hasMany 关系,那么您就不需要处理生成的集合了。相反,你可以在你的"项目"中添加一个简单的字段。使用Schema Builder的表和更新迁移。

否则,如果您不想在表格中添加新字段,则可以随时在 Project 模型中添加新的访问者

...

class Project extends Model
{

    ...

    public function getPaidAttribute($value)
    {
        // example: write your logic here and put it in $value...
        return $value;
    }

    ...
}

此处有更多信息:http://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators

仅在更高级的情况下使用集合。希望它有用。

哦,以及有关使用自定义集合的更多信息:http://laravel.com/docs/5.1/eloquent-collections#custom-collections