当用户为文章点赞、收藏等操作时,可以使用toggle操作。
1 建立数据库表
php artisan make:migration create_posts_table --create=posts
php artisan make:migration create_favorites_table --create=favorites
2数据库创建字段
posts数据表
public function up()
{
Schema::create('posts',function(Blueprint $table){
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
favorites数据表
public function up()
{
Schema::create('favorites',function(Blueprint $table){
$table->increments('id');
//定义两个外键
$table->unsignedInteger('user_id');
$table->unsignedInteger('post_id');
$table->timestamps();
});
}
3 在ModelFactory.php文件中设置Post
database\factories\ModelFactory.php文件
$factory->define(App\Post::class, function(Faker\Generator $faker){
return[
//sentence和paragraph两个均不写成复数形式,如果写成复数形式则为数组
'title'=>$faker->sentence,
'body'=> $faker->paragraph,
];
});
4 配置数据库
打开.env文件
链接数据库即可!
5 生成随机测试数据
php artisan tinker
http://laravelacademy.org/post/4935.html
生成随机数据
//生成5个用户
factory(App\User::class,5)->create()
//生成5个post
factory(App\post::class,5)->create()
6 在User.php中配置
App\User.php
public function favorites()
{
//传入数据库表表名favorites,如果不传入这个数据库表表名的话,则默认是的post_user。
return $this->beLongToMany(Post::class,'favorites');
}
7 读取数据
重新链接tinker,以获取刚才代码内容。
attach方法使用 attach、detach方法的调用需要if等判断语句来判断,然后执行操作。
php artisan tinker
获取数据库内容
//获取id为3的用户
$user=App\User:find(3)
//获取id为2的post
$post=App\Post::find(2)
//调用attach方法,与之相反的方法是detach
$user->favorites()->attach($post)
//获取User的favorites,如果直接执行favorites操作,则获取不到数据,
//$user->favorites
//刷新一下再进行favorites操作
$user->fresh()->favorites
此时会显示出用户收藏信息——id为3的用户收藏了post为2的数据。
pivot:Illustrate\Database\Eloquent\Relations\Pivot {#682
user_id:"3",
post_id:"2",
}
toggle方法的使用
//链接tinker
php artisan tinker
//调用toggle方法,写入到favorites数据库表中
$user->favorites()->toggle($post)
//此时会显示
[
"attached"=>[
2,
],
"detached"=>[],
]
//从favorites数据表中取出数据
$user->fresh()->favorites
//此时就可以取出数据
pivot:Illustrate\Database\Eloquent\Relations\Pivot {#682
user_id:"3",
post_id:"2",
}
如果favorites数据表中已经存在数据,若再执行toggle时则会删除数据
$user->favorites()->toggle($post)
//此时会显示,此时执行的时detached方法
[
"attached"=>[],
"detached"=>[
2,
],
]
//再次执行favorites方法
$user->fresh()->favorites
//显示
Illuminate\Datebase\Eloquent\Collection {#702
all:[],
}