项目作者: mits87

项目描述 :
Nested attributes allow you to save attributes on associated records through the parent.
高级语言: PHP
项目地址: git://github.com/mits87/eloquent-nested-attributes.git
创建时间: 2017-08-29T13:23:43Z
项目社区:https://github.com/mits87/eloquent-nested-attributes

开源协议:MIT License

下载


eloquent-nested-attributes

Latest Version on Packagist
Software License
Build Status
Total Downloads

Nested attributes allow you to save attributes on associated records through the parent. By default nested attribute updating is turned off and you can enable it using the $nested attribute. When you enable nested attributes an attribute writer is defined on the model.

Structure

If any of the following are applicable to your project, then the directory structure should follow industry best practises by being named the following.

  1. src/
  2. tests/
  3. vendor/

Install

Via Composer

  1. $ composer require mits87/eloquent-nested-attributes

Usage

  1. namespace App;
  2. use Eloquent\NestedAttributes\Model;
  3. class Post extends Model
  4. {
  5. protected $fillable = ['title'];
  6. protected $nested = ['option', 'comments'];
  7. public function option() {
  8. //it can be also morphOne
  9. return $this->hasOne('App\Option');
  10. }
  11. public function comments() {
  12. //it can be also morphMany
  13. return $this->hasMany('App\Comment');
  14. }
  15. }

or

  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. use Eloquent\NestedAttributes\Traits\HasNestedAttributesTrait;
  4. class Post extends Model
  5. {
  6. use HasNestedAttributesTrait;
  7. ...
  8. }

usage:

  1. \App\Post::create([
  2. 'title' => 'Some text',
  3. 'option' => [
  4. 'info' => 'some info'
  5. ],
  6. 'comments' => [
  7. [
  8. 'text' => 'Comment 1'
  9. ], [
  10. 'text' => 'Comment 2'
  11. ],
  12. ]
  13. ]);
  14. \App\Post::findOrFail(1)->update([
  15. 'title' => 'Better text',
  16. 'option' => [
  17. 'info' => 'better info'
  18. ],
  19. 'comments' => [
  20. [
  21. 'id' => 2,
  22. 'text' => 'Comment 2'
  23. ],
  24. ]
  25. ]);

to delete nested row you should pass _destroy attribute:

  1. \App\Post::findOrFail(1)->update([
  2. 'title' => 'Better text',
  3. 'option' => [
  4. 'info' => 'better info'
  5. ],
  6. 'comments' => [
  7. [
  8. 'id' => 2,
  9. '_destroy' => true
  10. ],
  11. ]
  12. ]);

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

  1. $ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email mits87@gmail.com instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.