gpt4 book ai didi

php - 如何在 codeigniter 中播种数据

转载 作者:搜寻专家 更新时间:2023-10-31 21:50:39 26 4
gpt4 key购买 nike

迁移后如何在 CodeIgniter 中播种数据?迁移完成后,我想在表用户迁移后播种一些预定义用户。

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Users extends CI_Migration {

public function up()
{
$this->load->database();
$dbprefix = $this->db->dbprefix;
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' =>11,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'first_name' => array(
'type' => 'VARCHAR',
'constraint' => 50
),
'last_name' => array(
'type' => 'VARCHAR',
'constraint' => 50,
)
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('users');
}

public function down()
{
$this->dbforge->drop_table('users');
}
}

最佳答案

我知道这篇文章很老了,但它是在谷歌中搜索“code igniter seeding in migration”时出现的第一个结果。所以我想我会提供我的解决方案。

您可以很容易地在迁移的 up 和 down 方法中执行简单的 $this->db->query($sql) 方法。

对于我的特殊情况,我正在播种一些静态哈希数据,因此将这些值放在迁移的属性中,并在循环中从中读取,每次从我的种子数组创建 SQL 插入查询。

这是我的种子迁移文件的一个经过编辑的简化示例:

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Seed_hash_table extends CI_Migration {

public function up()
{
foreach ($this->seedData as $seed ) {
$sql = 'INSERT INTO hash_table VALUES '.$seed;
$this->db->query($sql);
}
}

public function down()
{
foreach ($this->seedData as $seed) {
$hash = substr($seed, 2, 32);
$sql = 'DELETE FROM hash_table WHERE hash = \''.$hash.'\'';
$this->db->query($sql);
}
}

private $seedData = array(
'("2a96e53846b6232662fff87128061bbd", "Value A",)',
'("7c78ebb4c223c96fa9c5e6s3f73cc28e", "Value B",)',
'("ad2cb75a968ca5ef3255d924076e902f", "Value C",)',
);
}

注意:上面的示例已删除所有错误检查以保持较小的尺寸以便发布。

这当然依赖于您的数据架构(在之前的迁移中),并且您的 $seedData 属性中的所有值都是后者/右侧您的 INSERT 查询,并指定了所有列。

但是你明白了。 =)

关于php - 如何在 codeigniter 中播种数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934009/

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