【发布时间】:2018-11-05 16:21:51
【问题描述】:
我创建了 upvote/downvote 功能,它使用了一个名为 voted 的表。该表中的每条记录都包含一个 id、user_id、image_id 和整数投票(1 表示赞成,0 表示反对)。我的图像表包含 2 列,一列表示赞成票数,一列表示反对票数。
现在的问题是我不确定如何准确更新图像表中的赞成/反对列以及何时更新它们。我认为我应该在投票后立即这样做,但我不完全确定。
任何帮助将不胜感激。
投票模型:
class Vote extends Model
{
public function images(){
return $this->belongsTo('App\Images');
}
}
图像模型:
class Image extends Model
{
public function votes(){
return $this->hasMany('App\Vote');
}
}
图片表:
Schema::create('images', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->string('name');
$table->string('description')->nullable()->default(null);
$table->integer('user_id')->unsigned();
$table->string('file_name');
$table->string('upvotes')->default(0);
$table->string('downvotes')->default(0);
$table->string('views')->default(0);
$table->timestamps();
$table->engine = 'InnoDB';
});
投票表:
Schema::create('votes', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('user_id')->unsigned();
$table->integer('image_id')->unsigned();
$table->boolean('vote');
$table->timestamps();
$table->engine = 'InnoDB';
});
投票控制器
class VotesController extends Controller
{
public function voteImage(Request $request){
$image_id = $request['imageId'];
$isLike = $request['isLike'] === 'true';
$update = false;
$image = Image::find($image_id);
if (!$image){
return null;
}
$user = Auth::user();
$vote = $user->votes()->where('image_id', $image_id)->first();
if ($vote) {
$already_vote = $vote->vote;
$update = true;
if ($already_vote == $isLike){
$vote->delete();
return null;
}
} else {
$vote = new Vote();
}
$vote->vote = $isLike;
$vote->user_id = $user->id;
$vote->image_id = $image->id;
if ($update) {
$vote->update();
} else {
$vote->save();
}
return null;
}
}
【问题讨论】:
-
您是为了解决方案还是代码审查?