laravel toggle方法

toggle方法主要用于多对多关系中,attach detach 好比点赞 收藏post

1.user表this

2.post表 title contentcode

3.中间表 favoriate user_id post_idit

4.user中定义关系io

public function favorites(){
    return $this->belongsToMany(Post::class,'favoriates'); //第二个参数中间表
}

5.关联关系function

作法一:class

在tinker中操做方法

$user = App\User::find(1);
$post = App\Post::find(2);
$user->favorite()->attach($post);
查看结果:$user->refresh()->favorite

//取消收藏
 $user->favorite()->detach($post);

作法二:toggle 不用去判断用户有没有收藏该文章 用户收藏了则取消收藏 反之则收藏co

$user->favorite()->toggle($post);
相关文章
相关标签/搜索