【问题标题】:How to copy datas from one table into another one with all columns but not id in Laravel?如何在 Laravel 中将数据从一个表复制到另一个包含所有列但没有 id 的表中?
【发布时间】:2020-09-16 20:02:30
【问题描述】:

我使用 Laravel 6.x,我需要将数据从一个表复制到另一个表。像往常一样,两个表都有很多列,我正在寻找一个不依赖列名的解决方案。将来可能会更改列,我不想在每次更改时都触及软件的这一部分。

我想做这样的事情:

INSERT INTO product_copys (SELECT * from products);

我想复制products 表中没有id 的所有列。

我使用Product 和ProductCopy 模型来处理这些数据。

在 Laravel,Eloquent 中是否有任何方便的解决方案?

【问题讨论】:

  • 不知道有没有不涉及列名的解决方案。您的程序或 dbms 如何知道哪些列匹配以及哪些列具有不同的名称?
  • laravel 模型包含列名。
  • 是的,但是您的程序如何自行确定哪一列需要放在哪里?你需要在某个时候告诉它。
  • 我可以说Product::$fillable吗?或者如果我在模型上构建一个带有可备份字段的自定义数组,那么第二个更好的选择,然后说Product::select($backupableFields)...?

标签: php laravel eloquent laravel-6


【解决方案1】:

你可以使用以下

在您的App\Product 模型中

class Product extends Model
{

    protected $hidden = ['id'];
    //...
}

然后在你的控制器中

$copy = Product::all()->toArray();

ProductCopy::insert($copy);

如果您需要处理大量(数千)条 Eloquent 记录,请使用 chunk 命令将允许您在不吃掉所有 RAM 的情况下进行操作:

Product::chunk(200, function($products)
{
    ProductCopy::insert($products->toArray());
});

https://laravel.com/docs/7.x/eloquent#chunking-results

【讨论】:

  • 是的,这是我想要避免的:列出所有列。而这个解决方案结果改为查询一个
  • 我看到了 Product::all()->toArray() 导致 Laravel 将记录读入内存。我不想阅读它,我只想运行一个没有任何 PHP 模型处理的 SQL 查询。这种 read-chunk-insert 方法会浪费资源并且会花费更多时间。
【解决方案2】:

我找到了一个解决方案来获取没有id 列的列(感谢Laravel Tricks)。这是Product 模型的代码:

    /**
     * Get all columns of model
     *
     * @return Array
     */
    public static function getTableColumns() {
        $model = new Product();
        return $model->getConnection()
            ->getSchemaBuilder()
            ->getColumnListing($model->getTable());
    }

    /**
     * Return model's columns without given columns
     *
     * @param Array $without_columns
     * @return Array
     */
    public static function withoutColumn(Array $without_columns) {
        return array_diff(self::getTableColumns(), $without_columns);
    }

你可以在这里使用它:

$columns = Product::withoutColumn(['id']);

现在只需在控制器中运行原始 SQL 查询:

    public function backup() {
        $columns = implode(',', Product::withoutColumn(['id']));

        DB::statement('INSERT INTO product_copys ('.$columns.', date_of_backup) (SELECT ' .
            $columns .', NOW() AS date_of_backup FROM products)');

        return Response::HTTP_OK;
    }

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2015-07-18
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    相关资源
    最近更新 更多