首先建立一个简单的文章和标签表来演示 replicate()
方法的实用。
- 建立表和迁移文件
# wanli @ wanlideMacBook-Pro in /Applications/MAMP/htdocs/iTest [20:14:03]
$ php artisan make:model Models/article -m
Model created successfully.
Created Migration: 2016_06_16_121430_create_articles_table
# wanli @ wanlideMacBook-Pro in /Applications/MAMP/htdocs/iTest [20:14:30]
$ php artisan make:model Models/tag -m
Model created successfully.
Created Migration: 2016_06_16_121450_create_tags_table
- 文章数据结构
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticlesTable extends Migration {
/** * Run the migrations. * * @return void */
public function up() {
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->default('')->comment('文章标题');
$table->text('content')->comment('文章内容');
$table->timestamps();
});
}
/** * Reverse the migrations. * * @return void */
public function down() {
Schema::drop('articles');
}
}
- 标签数据结构
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagsTable extends Migration {
/** * Run the migrations. * * @return void */
public function up() {
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->default('')->comment('标签名称');
$table->timestamps();
});
}
/** * Reverse the migrations. * * @return void */
public function down() {
Schema::drop('tags');
}
}
简单使用
首先我们在文章表中插入一条数据:
Article::find(1)->replicate()->save();
dd(Article::all()->toArray());
在页面中显示:
复制并修改其中的一部分数据
如果要修改其中的一部分数据,只需要将复制出来的对象赋值给一个变量,然后改变其中的数据再 save()
就可以了:
$article = Article::find(1)->replicate();
$article->title = 'Laravel 复制数据并修改标题';
$article->save();
dd(Article::all()->toArray());
复制模型及关系
将文章的标签也一同复制,文章与标签之间的关系我就不展示了,这里直接贴代码:
$article = Article::with('tags')->find(1);
$clone = $article->replicate();
// 复制关系
$clone->push();
foreach($article->tags as $tag)
{
$clone->tags()->attach($tag);
}
OK,今天的小技巧就到这里了,