使用 Laravel eloquent 将数据从一张表插入到另一张表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27861282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:39:48  来源:igfitidea点击:

insert data from one table to another with laravel eloquent

phplaravellaravel-4eloquent

提问by baao

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?

哪个有效,但复制 2500 个条目需要大约 3 分钟,这是不正确的。有没有办法直接用eloquent复制数据,不用先把数据存到内存中?

回答by Marco Andrade

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

你可以只使用Eloquent::insert(). 例如:

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

Coder::insert($data);

Maybe thisquestion can help you!

或许这个问题可以帮到你!