filipedtristao / laravel-crud-builder

v0.0.2 2020-06-29 20:14 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。