云计算百科
云计算领域专业知识百科平台

laravel5.8用DB::statement加SQL语句来设置或者取消表字段id的主键属性

软件环境是windows10、apache2.4,php7.2,laravel5.8。

1、先用语句创建了test数据表:    

        $data = DB::statement('create table test (id INT)');

2、接着给该表添加字段name:
    $data = DB::statement('alter table test add name varchar(32) not null');

3、然后设置字段id为主键字段:

    $data = DB::statement('alter table test add primary key (id)');

4、给字段id添加非空,自动增加属性:

    $data = DB::statement('alter table test modify column id int not null auto_increment');

5、然后删除字段id的主键属性:

    $data = DB::statement('alter table test drop primary key');

这时更新页面时报错。

此时删除字段id的主键属性有两种方法可行:

        (1),直接删除id字段:
                    $data = DB::statement('alter table test drop column id');

        (2),先取消id字段的自动增加属性,然后去掉id字段的主键属性:

                    $data = DB::statement('alter table test modify column id int not null');

                    $data = DB::statement('alter table test drop primary key');

到这里已看到问题的原因:字段的自动增加属性会阻止去掉字段的主键属性。

6、要增加id字段的主键属性,有两种方法:

        (1),$data = DB::statement('alter table test add primary key (id)');

         (2),$data = DB::statement('alter table test modify column id int not null primary key auto_increment');

 7、如果最开始用一条简单的语句创建了一个表格的一个字段:

        $data = DB::statement('create table test (id INT)');

然后想给该字段添加几个属性,可以使用下面这条语句:

         $data = DB::statement('alter table test modify column id int not null primary key auto_increment');

8、将id字段移动到第一字段:

       $data = DB::statement('alter table test modify column id int not null  auto_increment first');

9、在laravel里,任何一步想显示结果,可以使用这条语句:
    dump($data);

赞(0)
未经允许不得转载:网硕互联帮助中心 » laravel5.8用DB::statement加SQL语句来设置或者取消表字段id的主键属性
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!