{
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->after('id');
});
}
database/migrations/2018_01_18_142146_create_favorites_table.php
public function up()
{
Schema::create('favorites', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->timestamps();
});
}
该 favorites 表包含两列:
user_id 被收藏文章的用户ID。
post_id 被收藏的帖子的ID。
然后进行表迁移
php artisan migrate1.4 用户认证
因为我们之前就已经创建过了,所以这里就不需要重复创建了。
如果你没有创建过用户认证模块,则需要执行 php artisan make:auth
2. 完成搜藏夹功能
修改 routes/web.php
2.1 创建路由器
Auth::routes();
Route::post('favorite/{post}', 'ArticleController@favoritePost');
Route::post('unfavorite/{post}', 'ArticleController@unFavoritePost');
Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');2.2 文章和用户之间多对多关系
由于用户可以将许多文章标记为收藏夹,并且一片文章可以被许多用户标记为收藏夹,所以用户与最收藏的文章之间的关系将是多对多的关系。要定义这种关系,请打开 User 模型并添加一个 favorites() app/User.php
注意 post 模型的命名空间是 AppModelsPost 所以注意要头部引入 use AppModelsPost;
public function favorites()
{
return $this->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')->withTimeStamps();
} 第二个参数是数据透视表(收藏夹)的名称。第三个参数是要定义关系(User)的模型的外键名称(user_id),而第四个参数是要加入的模型(Post)的外键名称(post_id)。 注意到我们链接withTimeStamps()到belongsToMany()。这将允许插入或更新行时,数据透视表上的时间戳(create_at和updated_at)列将受到影响。
2.3 创建文章控制器
因为我们之前创建过了,这里也不需要创建了。
如果你没有创建过,请执行 php artisan make:controller ArticleController
2.4 在文章控制器添加 favoritePost 和 unFavoritePost 两个方法
注意要头部要引入 use IlluminateSupportFacadesAuth;
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsPost;
use IlluminateSupportFacadesAuth;










