zoukankan      html  css  js  c++  java
  • laravel toggle方法

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

    1.user表

    2.post表 title content

    3.中间表 favoriate user_id post_id

    4.user中定义关系

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

    5.关联关系

    做法一:

    在tinker中操作

    $user = AppUser::find(1);
    $post = AppPost::find(2);
    $user->favorite()->attach($post);
    查看结果:$user->refresh()->favorite
    
    //取消收藏
     $user->favorite()->detach($post);
    

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

    $user->favorite()->toggle($post);
  • 相关阅读:
    语文成语的积累
    关于翻译
    关于文常
    语文小说
    语文 散文阅读
    矩佬的博客
    字词
    语文病句
    地理
    寒假某cg的数学卷子....
  • 原文地址:https://www.cnblogs.com/webskill/p/7464403.html
Copyright © 2011-2022 走看看