laravel5.3-第7章-toggle laravel5.3-第7章-toggle

2023-06-29

一、下载 laravel 5.3

composer create-project laravel/laravel=5.3.* laravel5.3_toggle

新建数据库 laravel5.3_toggle

修改 .evn 配置文件

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5.3_toggle
DB_USERNAME=laravel5.3_toggle
DB_PASSWORD=laravel5.3_toggle

修改中国时区,在 config/app.php 中修改

'timezone' => 'PRC',

二、创建数据

切换目录

cd laravle5.3_toggle

创建 post model

php artisan make:model Post -m

app/User.php 新增方法

public function favorites()
{
   return $this->belongsToMany(App\Post::class, 'favorites');
}

创建 favorites migration

php artisan make:migration create_favorites_table --create=favorites

修改迁移文件:posts_table.php

public function up()
{
   Schema::create('posts', function (Blueprint $table) {
       $table->increments('id');
       $table->string('title');
       $table->string('content');
       $table->timestamps();
   });
}

修改迁移文件:favorites_table.php

public function up()
{
   Schema::create('favorites', function (Blueprint $table) {
       $table->increments('id');
       $table->unsignedInteger('user_id');
       $table->unsignedInteger('post_id');
       $table->timestamps();
   });
}

修改 database/factories/ModelFactory.php

$factory->define(App\Post::class, function (Faker\Generator $faker) {
   return [
       'title' => $faker->sentence,
       'content' => $faker->paragraph,
   ];
});

执行数据迁移

php artisan migrate

创建用户数据

php artisan tinker
factory('App\User', 5)->create();

创建文章数据

factory('App\Post', 5)->create();

三、attach

进入 tinker

查找第一个用户

$user = App\User::find(1)

查找第一篇文章

$post = App\Post::find(1)

查看用户收藏的文章

$user->favorites

https://file.lulublog.cn/images/3/2023/06/GCnNNNN4zPplQt0XcipInnQ0xGIxTM.jpg

收藏文章

$user->favorites()->attach($post)

再次查看用户收藏的文章

$user->fresh()->favorites

https://file.lulublog.cn/images/3/2023/06/f6uuqo02S0U06pzN00fA06Qy36Ysj3.png

可以看到有收藏数据

注意:需使用 fresh() 刷新再查找,否则会使用缓存

取消收藏文章

$user->favorites()->detach($post)

再次查看用户收藏的文章

$user->fresh()->favorites

发现收藏的文章列表为空

四、toggle

收藏文章

$user->favorites()->toggle($post)

查看用户收藏的文章

$user->fresh()->favorites

可以看到有收藏数据了

取消收藏文章

$user->favorites()->toggle($post)

查看用户收藏的文章

$user->fresh()->favorites

发现收藏的文章列表为空

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

阅读 227