将新属性引入laravel集合对象

raa*_*man 1 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 ?}
Run Code Online (Sandbox Code Playgroud)

小智 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;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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