【问题标题】:Laravel: Save uuidv4 to databaseLaravel:将 uuidv4 保存到数据库
【发布时间】:2021-07-18 05:50:54
【问题描述】:

我正在使用 ReactLaravel 来创建列表。 在添加按钮中,我有以下内容

 function handleAdd() {
    const newList = list.concat({ name, id: uuidv4(), value });
    setList(newList);
    setName("");
    setValue("");
  }

const onAddSocial = (e) => {
  e.preventDefault();

const test = {
  value: value,
  name: name,
};

axios.post('http://localhost:8000/api/social', test)
  .then((res) => {
    toast(<div class="text-primary font-weight-bolder">Social link added successfully!</div>,{ delay: 0 });
    console.log(res)
  }).catch((error) => {console.log(error)
  })

}

以及触发这两个创建功能的按钮:

 <Button                  
                onClick={(e) => {
                  props.handleAdd();
                  props.onAddSocial(e);
                }}
              >

元素已创建,但在数据表中id 收到一个递增值。 如何改为传递已创建元素的 uuidv4() ?

商店控制器:

public function store(Request $request)
{
    $data = new Social();
    $data->value = $request->value;
    $data->name = $request->name;
    $data->save();
}

【问题讨论】:

    标签: reactjs laravel


    【解决方案1】:

    您必须使用以下代码

    在你的Social Model中你必须这样使用

    public $incrementing = false;
    
    protected $keyType = 'string';
    
    
    public static function boot(){
        parent::boot();
    
        static::creating(function ($social) {
            $social->id = Str::uuid(36);
        });
    }
    

    在标题部分添加这一行

    use Illuminate\Support\Str;
    

    在您的 database\migration 社交文件中还添加以下代码

    public function up()
    {
        Schema::create('socials', function (Blueprint $table) {
            $table->uuid('id', 36)->primary();
            $table->timestamps();
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 2020-01-15
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 2016-12-13
      • 1970-01-01
      相关资源
      最近更新 更多