1 回答
TA贡献2080条经验 获得超4个赞
你不需要value一个like,如果它存在,它是一个“like”,你应该使用 is 作为一个数据透视表(你已经有 2 个外国 ID)
Schema::create('likes', function (Blueprint $table) {
$table->unsignedInteger('post_id');
$table->unsignedInteger('user_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->tinyInteger('is_dislike')->default(0);
$table->timestamps();
});
Post然后声明和之间的关系User
邮政
public function votedUsers(){ //or simply likes
return $this->belongsToMany(User::class, 'likes')->withPivot('is_dislike')->withTimestamps();
}
用户
public function votedPosts(){
return $this->belongsToMany(Post::class, 'likes')->withPivot('is_dislike')->withTimestamps();
}
接下来创建一个like 就这样做
public function liker($postId, $userId, $value){
$user = User::findOrFail($userId); //or use auth()->user(); if it's the authenticated user
$user->votedPosts()->attach($postId);
return redirect()->back();
}
改为删除类似的使用detach($postId)。
对于不喜欢
$user->votedPosts()->attach($postId, ['is_dislike' => 1]);
- 1 回答
- 0 关注
- 106 浏览
添加回答
举报