【问题标题】:Fetch data for a select query in yii migrations在 yii 迁移中获取选择查询的数据
【发布时间】: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-&gt;id 之类的东西来获取父 ID 以批量插入子记录。
  • @MichalHynčica:我想创建一个迁移脚本,以便将来如果我们要迁移整个数据库,这些值将直接插入到一个迁移中,而不是使用 foreach 创建脚本。由于记录是静态的,无论如何它只是一个一次性脚本。

标签: yii yii2 yii-migrations


【解决方案1】:

你需要使用

$sql = <<<SQL
select * from parent_table where name = 'P1'
SQL;

$res = Yii::$app->db->createCommand($sql)->queryAll();

$this-&gt;execute() 用于执行更新或删除等 sql 语句

编辑

最好使用$this-&gt;db 而不是Yii::$app-&gt;db 以确保您在同一个数据库上运行,如 cmets 中所述

【讨论】:

  • 使用$this-&gt;db 组件而不是Yii::$app-&gt;db 可能会更好,以确保您在同一个数据库上运行查询。
猜你喜欢
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 2014-11-02
  • 2023-03-24
相关资源
最近更新 更多