当我使用save()方法或使用create
或update
等分开的调用时,如何强制laravel始终创建新记录。
例如,我想从表中获取一些记录,修改它们并将它们保存为新记录。
$products = Product::where('category_id', 10)->get();
foreach( $products as $product ){
$product->name = 'new name';
$product->save();
}
以上脚本,更新记录,在phalconphp
我可以具体说出$product->create()
并创建新记录。
Laravel有可能吗?
答案 0 :(得分:3)
这是使用replicate
克隆模型的更简单方法:
$products = Product::where('category_id', 10)->get();
foreach( $products as $product )
{
// Clone the model
$clone = $product->replicate();
// Apply any changes you want to the cloned model
$clone->name = 'new name';
// ...
// Save the cloned/modified model as a different record
$clone->save();
}
答案 1 :(得分:1)
为什么不......
$products = Product::where('category_id', 10)->get();
foreach( $products as $product ){
$new_product = new Product();
$new_product->name = 'new name';
$new_product->other_column = $product->other_column;
$new_product->save();
}
答案 2 :(得分:0)
也许您需要以下内容?创建一个新产品,您可以从现有产品中设置其属性,也可以分配新值。
$products = Product::where('category_id', 10)->get();
foreach( $products as $product ){
$newproduct = new Product;
$newproduct ->name = $product->name; // or assign a new value
$newproduct ->attribute1 = $product->attribute1; // or assign a new value
$newproduct ->attribute2 = $product->attribute2;// or assign a new value
$newproduct ->attribute3 = $product->attribute3;// or assign a new value
$newproduct ->save();
}