I have 3 models inside a Laravel application:
User
Question
Alternative
Some model relations:
Question
can have many Alternative
. Alternative
belongs to one Question
There's a pivot table which stores an answer by an user. It stores the user_id
and the alternative_id
.
In the pivot table, how can I delete all answers from a specific Question
? (I have the question_id
)
You can use detach as well sync method but you have to define relationships first in your models e.g
public class Question extends Model {
public function alternatives() {
return $this->hasMany(Alternative::class);
}
}
public class Alternative extends Model {
public function users() {
return $this->belongsToMany(User::class);
}
}
and than
$question = Question::findOrFail('question_id');
$question->alternative()->user()->sync();
or
$question->alternative()->user()->detach();