大头

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 = \App\Post::find(2);
    $newUser = \App\User::find(1);
    $newUser->posts()->attach($post);
});

查看数据:

image

 

detach 清除数据库中的数据

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

    $post = \App\Post::find(2);
    $newUser = \App\User::find(1);
    $newUser->posts()->detach($post);
});

image

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

posted @ 2017-03-03 15:11  and大头  阅读(536)  评论(0编辑  收藏  举报

大头