mercredi 13 septembre 2017

Laravel update pivot table (many to many relationship)

I have for tables named users, questions, answers and answer_user. I can get data from tables using $user->answers method but I couldn't figure out how to update or insert if not exists. (answer_user table)

user table:

$table->increments('id');
$table->string('email', 255)->unique();
$table->string('password', 255);

questions table:

$table->increments('id');
$table->string('title', 255);

answers table:

$table->increments('id');
$table->string('text');
$table->integer('question_id')->unsigned();


$table->foreign('question_id')
      ->references('id')
      ->on('questions')
      ->onDelete('cascade');

answer_user table

$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');

My models:

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');
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire