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);
相關文章
相關標籤/搜索