laravel中的attach and detach toggle method

创建模型 post  and  user 以及 users , posts ,user_post(favorities)测试数据

    在此可以看上一篇中的数据,本次测试数据利用的上一篇的数据。detach and attach  method  在很多地方 都可以用到 而且非常方便,不用自己查询数据库后在判断是否存在,再添加数据狡猾

attach  and  detach method

在关联表中添加数据 :

Route::get('/', function () {

    $post = AppPost::find(2);
    $newUser = AppUser::find(1);
    $newUser->posts()->attach($post);
});

查看数据:

image

detach 清除数据库中的数据

Route::get('/', function () {

    $post = AppPost::find(2);
    $newUser = AppUser::find(1);
    $newUser->posts()->detach($post);
});

image

toggle方法就是detach 与 attach 的结合,跟jQuery中的toggle方法差不多。

原文地址:https://www.cnblogs.com/webph/p/6496783.html