当有人投票时,我会将其存储在数据库中,如下所示:
public function store(Option $option)
{
$option->votes()->sync([Auth::user()->id]);
}
数据透视表如下所示:
id
option_id
user_id
如何确保当用户已经投票,然后投票支持其他投票时,其他投票就会消失?
sync方法只查找id。
答案 0 :(得分:2)
我将如何做:
数据库:
Poll
- name
Option
- value
- poll_id
Vote
- poll_id
- option_id
- user_id
关系:
class Poll extends Model
{
public function options ()
{
return $this->hasMany(Option::class);
}
public function votes ()
{
return $this->hasMany(Vote::class);
}
}
class Option extends Model
{
public function poll ()
{
return $this->belongsTo(Poll::class);
}
}
class Vote extends Model
{
public function poll ()
{
return $this->belongsTo(Poll::class);
}
public function option ()
{
return $this->belongsTo(Option::class);
}
public function user ()
{
return $this->belongsTo(User::class);
}
}
class User extends Model
{
public function votes ()
{
return $this->hasMany(Vote::class);
}
}
避免用户可以为多个选项投票的代码:
// We first remove any eventually vote from this user on this poll
$user->votes()->where('poll_id',$poll->id)->delete();
// We then create a vote for the user
$user->votes()->create([
'poll_id' => $poll->id,
'option_id' => $option->id
]);
这将为您提供更大的灵活性。例如,您可以使用此代码,通过投票列出用户和投票之间的hasManyThrough
关系,以列出某个用户的所有民意调查