Laravel 在其他列上同步

Laravel sync on other column

我进行了投票。民意调查有选项,选项有选票。

当有人投票时,我会像这样将其存储在数据库中:

public function store(Option $option)
{
    $option->votes()->sync([Auth::user()->id]);
}

支点 table 看起来像这样:

id
option_id
user_id

我如何确保当用户已经投票,然后投票给其他东西时,另一票消失?

sync 方法只是在寻找 id。

这是我的做法:

数据库:

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 关系,以列出特定用户的所有民意调查