点赞模块
1、赞模块表设计
在laravel中使用 php artisan make:migration Zans
post_id int
user_id int
当文章完成点赞的时候,直接在表中创建一条新的记录。
当取消点赞的时候,直接将表中的一条记录直接删除即可。
通过下面的操作进行数据库表的创建:
migration详细细节:
最后执行 php artisan make:migrate 进行表创建。
创建Zans Model模型
E:\phpStudy\WWW\internet-cloud-hospital>php artisan make:model ZansModel Model created successfully.
php artisan make:model ZansModel
即可完成zans 模型的创建。
例如:
Zans关联模型设置 完成zan的业务逻辑
1、是否已经对此文章点赞过
<?php namespace App\Model; use Illuminate\Database\Eloquent\Model as CoreModel; class Post extends CoreModel{ // 这个方法的意思是:查找当前用户user_id 对这篇文章是否有点击过赞 // withCount('zan'); 通过这样的方式获取数量 public funciton zan($user_id){ return $this->hasOne(Comments::class)->where('user_id',$user_id); } //获取这篇文章所有的点赞量 public function zans(){ return $this->hasMany(Comments::class); } }
2、对文章进行点赞操作
<?php namespace App\Http\Controllers; class Post { //文章点赞 public function zan(){ //常规逻辑 $userId=Auth::id(); $postId=request('id'); $count = Zans::query()->where('post_id',$postId)->where('user_id',$userId)->count(); if($count==0){ //进行点赞 $params = [ 'post_id'=>$postId, 'user_id'=>$userId ]; Zans::query()->create($params); } //使用 firstOrCreate 方法写法 使用这种写法会更加方便 $params = [ 'post_id'=>$postId, 'user_id'=>$userId ]; Zans::query()->firstOrCreate($params); return 1; } //取消点赞 public function unzan(){ //常规写法 $userId=Auth::id(); $postId=request('id'); Zans::query()->where('post_id',$postId)->where('user_id',$userId)->delete(); //关联模型写法 $posts = Post::find($postId); $posts->zan($userId)->delete(); //这句话的意思: 删除user_id 为userId的 , 且post_id 为 $postId 的评论. } }
3、对此篇文章取消点赞操作
判断当前用户是否对此文章有进行过点赞
if($post->zan(Auth::id())->exists()){
//点赞过
}else{
//没有点赞过
}