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