【问题标题】:Copying rows from one table to another without duplicates using eloquent/fluent使用 eloquent/fluent 将行从一个表复制到另一个表而不重复
【发布时间】:2015-06-12 03:17:30
【问题描述】:
 $product = Book::select('name', 'id', 'user_id')->where('books.user_id', '=', 1)
        ->whereNotExists(function($query)
        {
            $query->select(DB::raw(3))
                  ->from('music')
                  ->whereRaw('music.name = books.name');

        })
        ->get();

上面的代码从书表中为单个用户选择 3 行,其中书表和音乐表之间没有重复名称。但是我想要做的实际上是将这些行复制到音乐表中。

所以我想这样做

$product = Book::select('name', 'id', 'user_id')->where('books.user_id', '=', 1) 

并将这些行复制到音乐表中而不重复名称?还有没有一种方法可以复制所有行而不必选择行数?

【问题讨论】:

  • 我建议您忽略您的数据库模式,当您必须在两个表之间复制相同的信息时,您似乎正在存储冗余数据。尝试规范化您的表格。我知道这不是您要寻找的答案,这只是一个一般性提示。
  • 感谢@henrik 的提示,但是我这样设计我的数据库的原因是因为音乐表中有我不想放在任何其他表中的列。这些列对应于我要复制到其中的新行。

标签: sql laravel laravel-4 eloquent


【解决方案1】:

将您的 $product 变量重命名为 $products,因为它不止一个。

然后将您的查询保存到 musuc 表中意味着遍历产品:

// Get the books you want to copy
//using your query or you can also use (distinct()) to get unique records
// iterate through the books that have a unique name
foreach ($products as $product){
    // save them in your music table using either your model or an insert query
    $song = Music::create(array($product->name ...etc...));
}

【讨论】:

  • 谢谢@keithm。实际上,我不得不将数组作为键值对进行迭代,只获取值并为每个值分配一个变量,然后插入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 2017-11-02
  • 2014-09-22
相关资源
最近更新 更多