reactjs - Laravel:将 uuidv4 保存到数据库
问题描述
我正在使用React和Laravel创建列表。在添加按钮中,我有以下内容
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();
}
解决方案
您必须使用以下代码
在您的社交模型中,您必须像这样使用
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;
在您的数据库\迁移社交文件中添加以下代码
public function up()
{
Schema::create('socials', function (Blueprint $table) {
$table->uuid('id', 36)->primary();
$table->timestamps();
});
}
推荐阅读
- python - 如何用 matplotlib.pyplot 画一个圆
- java - 对于什么类型的 A 和 B,简单的赋值语句 A = B 在 Java 中合法但在 C# 中不合法?
- node.js - 如果偏移量在文件范围内,为什么 Node.js 会抱怨 ERR_OUT_OF_RANGE?
- amazon-web-services - 如何优雅地关闭 Amazon ECS Fargate 任务?
- scala - 不使用var,在Scala中使静态值无效并稍后将其再次设置为新值的方法是什么
- haskell - Haskell - 如何将 Either 返回到我的自定义类型?
- reactjs - 使用 useEffect() 反应子级未在父状态更改时更新
- ruby - Ruby 错误:调用私有方法“执行”
- python-3.x - Tensorflow 2.3 -TypeError:获取参数 None 的类型无效
当使用 .get_session().run(tf.compat.v1.variables_initializer - selenium - 测试流媒体服务(如 selenium)