gpt4 book ai didi

php - Laravel 向数据库表中插入信息时,是否可以将某个表的列留空?

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:51 24 4
gpt4 key购买 nike

假设我有一个表格图像。表中的两个列是赞成票和反对票。填充表时是否需要插入 0 作为默认值,或者我可以省略 $image->upvotes = 0;$image->downvotes = 0;

class ImageController extends Controller
{
public function postUploadImage(Request $request){
$name = $request['name'];
$description = $request['description'];
$file = $request->file('image');

$image = new Image();
$image->name = $name;
$image->description = $description;
$image->file_name = 'dasdasd';
$image->upvotes = 0;
$image->downvotes = 0;
$image->views = 0;
$request->user()->images()->save($image);
return redirect()->back();
}
}

……

我的迁移:

public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->string('user_id');
$table->string('file_name');
$table->string('upvotes');
$table->string('downvotes');
$table->string('views');
$table->timestamps();
});
}

最佳答案

这取决于你的数据库结构。使用 column modifiers在您的迁移中执行此操作。

在您的情况下,将列默认设置为 0 是有意义的。例如:

Schema::table('images', function (Blueprint $table) {
// ...
$table->integer('upvotes')->default(0);
$table->integer('downvotes')->default(0);
});

然后您可以简单地省略在 Controller 中设置这些属性。


如果您不能简单地删除表并重新创建它(也许它已经在生产中运行并且您希望保留现有数据),请通过执行以下操作进行另一次迁移以修改现有表:

Schema::table('images', function ($table) {
$table->integer('upvotes')->default(0)->change();
$table->integer('downvotes')->default(0)->change();
});

关于php - Laravel 向数据库表中插入信息时,是否可以将某个表的列留空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48597222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com