1
我有名为用户,问题,答案和answer_user的表。我可以使用$ user-> answers方法从表中获取数据,但我无法弄清楚如何更新或插入(如果不存在)。 (answer_user表)Laravel更新数据透视表(多对多关系)
用户表:
$table->increments('id');
$table->string('email', 255)->unique();
$table->string('password', 255);
问表:
$table->increments('id');
$table->string('title', 255);
答案表:
$table->increments('id');
$table->string('text');
$table->integer('question_id')->unsigned();
$table->foreign('question_id')
->references('id')
->on('questions')
->onDelete('cascade');
个answer_user表
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('question_id')->unsigned();
$table->integer('answer_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('question_id')
->references('id')
->on('questions')
->onDelete('cascade');
$table->foreign('answer_id')
->references('id')
->on('answers')
->onDelete('cascade');
我的模型:
class Question extends Model
{
public function answer()
{
return $this->hasMany('App\Answer');
}
}
class Answer extends Model
{
public function question()
{
return $this->belongsTo('App\Question');
}
}
class User extends Authenticatable
{
public function answers()
{
return $this->belongsToMany('App\Answer');
}
}
它为什么不只是更新而不是添加新行? – Dejavu
如果你想在2表之间有任何关系,你必须添加新的行。或者你可以在关系存在的时候更新它 –
“关系存在时更新”是什么意思?以及我认为我已经拥有了? – Dejavu