🔥

CodeIgniter4 INSERT-SELECT をする

2022/10/27に公開

test_table2SELECT 結果を test_table1INSERT する場合

app\Models\TestTable1Model.php
<?php

namespace App\Models;

use CodeIgniter\Model;

class TestTable1Model extends Model
{
    protected $table = 'test_table1';
    protected $primaryKey = 'id';

    public function insertSelect()
    {
        $model = new TestTable2Model();
        $builder = $model->builder();
        $select = $builder->select('id, name')->getCompiledSelect();

        $sql = 'INSERT INTO test_table1 ' . $select;
        $this->db->query($sql);
    }
}
app\Models\TestTable1Model.php
<?php

namespace App\Models;

use CodeIgniter\Model;

class TestTable2Model extends Model
{
    protected $table = 'test_table2';
    protected $primaryKey = 'id';
}

Discussion