如何从 Laravel 迁移中的另一列添加相同的默认值



我的数据库中有一个questions表,其中有一列question_title,现在我添加了一个列question_slug,它将包含问题的 slug URL,所以我如何在 Laravel 迁移中将默认值设置为question_titlequestion_slug,我需要这一切,因为我有保存在数据库中的问题,所以我运行了php artisan make:migration add_column_to_questions --table=questions现在我有以下代码:

Schema::table('questions', function (Blueprint $table) {
$table->string('question_slug')->default();
});

首先,创建一个新的迁移并将以下代码放入其中:

connections_string:它在web/config/database.php文件中 配置

<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class NameOfUrMigration extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->string('question_slug')->default();
});
$questions = DB::connection('connections_string')->table('questions')->get();
foreach($questions as $question)
{
$question->question_slug = str_slug($question->question_title);
$question->save();
}

}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}

根据文档,default()用于Declare a default value for a column. 这意味着,如果未在insert查询中提供值,则默认情况下在字段中插入的值。

default()无法帮助您实现这里的需求。 您可以做的是在up()方法中使用原始查询创建一个新的迁移类,该类将使用question_title的值更新question_slug的值。

像这样:

public function up()
{
$sql = "UPDATE `questions` SET `question_slug` = `question_title` WHERE 1;"; 
//add filtering conditions if you don't want ALL records updated
DB::connection()->getPdo()->exec($sql);
}

请确保还为rollback创建相应的down()方法

最新更新