使用 eloquent/fluent 将行从一个 table 复制到另一个而不重复

Copying rows from one table to another without duplicates using eloquent/fluent

 $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();

上面的代码 selects 来自书籍 table 的 3 行对于单个用户,其中书籍 table 和音乐 table 之间没有重名.但是我想做的实际上是将这些行复制到 music table 中。

所以我想这样做

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

并将这些行复制到 music table 中而不重名?还有一种方法可以复制所有行而不必 select 行数吗?

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

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

// 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...));
}