Laravel update pivot table (many to many relationship) -
i have tables named users, questions, answers , answer_user. can data tables using $user->answers method couldn't figure out how 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'); } }
you can see reference here. when use attach, create new rows in answer_user table. if not want rows anymore, can detach it. or can use sync when want add new rows , detach old rows in answer_user table (sync = detach + attach again)
class question extends model { public function user() { //the question should belong user. } public function answers() { //if use hasmany, method should plural nouns return $this->hasmany('app\answer'); } } class answer extends model { //one answer should belong 1 question , 1 user public function user() { return $this->belongsto('app\user'); } public function question() { return $this->belongsto('app\question'); } } class user extends authenticatable { public function answers() { return $this->hasmany('app\answer'); } } if want use many many relationship, can imagine 1 question belongs many tags, , 1 tag has many questions. can define it.
class tag extends model { public function questions() { return $this->belongstomany('app\question'); } } class question extends model { public function tags() { return $this->belongstomany('app\tag'); } } if want have relationships, should define in tables. sorry because of english.
Comments
Post a Comment