【发布时间】:2021-05-11 16:30:40
【问题描述】:
我正在使用 yii 迁移创建一个父子表,其中子表上有一个外键。我尝试使用执行,但这并没有帮助我获取所需的数据。有没有办法可以查询父表并在子表上插入父ID作为外键?像 fetch()/fetchAll() 这样的东西在 phinx 迁移中使用。
$this->batchInsert('{{%parent_table}}',
['name'],
[
['P1'],
['P2'],
['P3'],
['P4']
]
);
$a = $this->execute("select * from parent_table where name = 'P1'");
// get the data from the table that will get me the id from the above query.
$this->batchInsert('{{%child_table}}',
[['name'],['parent_id']],
[
['C1','<parent id>'],
['C2','<parent id>'],
.
.
.
]
);
【问题讨论】:
-
您是否有不想使用 ActiveRecord 模型在父表中创建记录的原因?您可以在 for/foreach 循环中创建父记录,然后使用
$model->id之类的东西来获取父 ID 以批量插入子记录。 -
@MichalHynčica:我想创建一个迁移脚本,以便将来如果我们要迁移整个数据库,这些值将直接插入到一个迁移中,而不是使用 foreach 创建脚本。由于记录是静态的,无论如何它只是一个一次性脚本。
标签: yii yii2 yii-migrations