在表格中创建新列时,您可以使用 - > after('列名称)来指示它的去向。如何创建按我想要的正确顺序重新排序列的迁移?
答案 0 :(得分:20)
试试这个,希望它能帮助您找到正确的解决方案:
public function up()
{
DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}
public function down()
{
DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");
}
答案 1 :(得分:17)
如果您希望在不破坏数据的情况下执行此操作,则可以在执行架构更新的同时迁移数据:
use DB;
public function up()
{
//Give the moving column a temporary name:
Schema::table('users', function($table)
{
$table->renameColumn('name', 'name_old');
});
//Add a new column with the regular name:
Schema::table('users', function(Blueprint $table)
{
$table->string('name')->after('city');
});
//Copy the data across to the new column:
DB::table('users')->update([
'name' => DB::raw('name_old')
]);
//Remove the old column:
Schema::table('users', function(Blueprint $table)
{
$table->dropColumn('name_old');
});
}
答案 2 :(得分:6)
我建议使用DB :: query('.. raw sql query ..');并使用答案“How to move columns in a MySQL table?”
中的查询答案 3 :(得分:1)
假设您的列名称为Varchar(50)
,并且您希望对其位置进行重新排序,以便它位于另一个名为using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LOGINPAGE
{
public partial class Room : Form
{
public Room()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
FloorSelection ss = new FloorSelection();
ss.Show();
}
private void EXIT_Click(object sender, EventArgs e)
{
this.Close();
}
private void xButton1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mohamed\Documents\UserData.mdf;Integrated Security=True;Connect Timeout=30");
this.Hide();
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From dbo.[LOGIN] where username='" + username_txt.Text + "' and Password ='" + password_txt.Text + "'", con);
FloorSelection ss = new FloorSelection();
ss.Show();
}
}
}
的列之后,并且您的表名称为address
。
在您的终端中输入下一个命令:
city
您只能根据需要更改employees
和php artisan migrate:make reorganize_order_of_column_address --table=employees
,但保持命令的其余部分不变。
这会在reorganize_order_of_column_address
文件夹中生成一个迁移文件,打开它并将您的代码放在employees
函数中,如下所示:
app/database/migrations
请注意,此方法将删除列及其中存储的所有数据,并在您检测到的列之后创建一个具有相同名称的新列,并且新创建的列将为空。
这种方式在Laravel 4.2中适用于我,它也可以在Laravel 5中使用,但是在终端中输入的命令有一些变化。
答案 4 :(得分:0)
试试这个
public function up()
{
DB::statement("ALTER TABLE example CHANGE foo foo DATA_TYPE DATA_ATTRIBUTE(s) AFTER bar");
DB::statement("ALTER TABLE example CHANGE foo foo INT(10) UNSIGNED NOT NULL AFTER bar");
}
或者,如果你懒得弄明白SQL,你可以访问你的phpMyAdmin,点击你的数据库,点击你的表,点击结构选项卡,除了要移动的列,点击更改按钮,编辑最后一个移动column 列,单击“保存”按钮,然后复制 SQL。