Search code examples
phplaravellaravel-4eloquent

insert data from one table to another with laravel eloquent


I have two tables, one with a primary key that references another table's column. I now need to copy all the primary keys to the second table.

I have these two models:

class Products extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;


    protected $connection = 'mysql3';

    protected static $_table;

    public function setTable($table)
    {
        static::$_table = $table;
    }

    public function getTable()
    {
        return static::$_table;
    }

    public function skuEAN() {

        return $this->hasOne('SkutoEAN', 'seller_sku', 'seller_sku');


    }

and

class SkutoEAN extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;


    protected $connection = 'mysql3';

    protected static $_table;

    public function setTable($table)
    {
        static::$_table = $table;
    }

    public function getTable()
    {
        return static::$_table;
    }

    protected $fillable = ['seller_sku','EAN','fallback'];

    public function connectToproducts() {

        return $this->belongsTo('de_products');

    }

Now in my controller, I'm doing this:

$data = Products::get(['seller_sku']);
    foreach ($data as $a) {
        $skuean = SkutoEAN::create(['seller_sku' => $a->seller_sku]);
        $skuean->save();
}

Which is working, but takes about 3 minutes to copy 2500 entries, which can't be correct. Is there a way to copy the data directly with eloquent, without storing the data in the memory first?


Solution

  • You can just use Eloquent::insert(). For example:

    $data = array(
        array('name'=>'Coder 1', 'rep'=>'4096'),
        array('name'=>'Coder 2', 'rep'=>'2048'),
        //...
    );
    
    Coder::insert($data);
    

    Maybe this question can help you!