eloverde-sistemas/laravel-crud-builder

1.0.3 2023-01-06 03:08 UTC

This package is auto-updated.

Last update: 2024-09-06 06:35:28 UTC


README

此包允许您根据请求创建和更新Eloquent模型,并同步关系。请求参数名称尽可能遵循JSON API规范

注意:灵感来源于Spatie的查询构建器包

基本用法

根据请求创建模型

请求体

{
  data: {
    attributes: {
      name: 'Paul',
      age: 77
    }
  }
}

PHP控制器代码

  use CrudBuilder\CrudBuilder;
    
  $singer = CrudBuilder::for(Singer::class)
    ->allowedAttributes('age', 'name')
    ->create();
  
  //A singer is created in database with the request data 

根据请求更新模型

请求体

{
  data: {
    id: 1,
    attributes: {
      name: 'Paul',
      age: 77
    }
  }
}

PHP控制器代码

  use CrudBuilder\CrudBuilder;
    
  $singer = CrudBuilder::for(Singer::class)
    ->allowedAttributes('age', 'name')
    ->update();
  
  //A singer with the requested id is updated in database with the request data 

可以使用 ->createOrUpdate() 方法根据请求中ID的存在来创建或更新。

根据请求更新模型,忽略某些属性

请求体

{
  data: {
    id: 1,
    attributes: {
      name: 'Paul',
      surname: 'McCartney',
      age: 77
    }
  }
}

PHP控制器代码

  use CrudBuilder\CrudBuilder;
    
  $singer = CrudBuilder::for(Singer::class)
    ->ignoreAttributes('age', 'surname')
    ->allowedAttributes('name')
    ->update();
  
  //A singer with the requested id is updated in database with the request data, except the ignored attributes 

根据请求更新模型,包括关系

请求体

{
  data: {
    id: 1,
    attributes: {
      name: 'Paul'
    },
    relationships: {
      band: {
        data: {
          id: 1
        }
      }
    }
  }
}

PHP模型代码

class SingerModel extends Model
{
  public function band()
  {
      return $this->belongsTo(Band::class);
  }
}

PHP控制器代码

  use CrudBuilder\CrudBuilder;
    
  $singer = CrudBuilder::for(Singer::class)
    ->allowedAttributes('name')
    ->allowedRelations('band')
    ->update();
  
  //A singer with the requested id is updated in database with the request data, including the relationship 

注意:目前唯一支持的关系是:BelongsTo和HasMany。