Reputation: 713
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');
}
}
Upvotes: 0
Views: 718
Reputation: 493
You can see the reference here. When you use attach, it will create some new rows in answer_user
table. If you do not want this rows anymore, you can detach
it. Or you can use sync
when you want to add new rows and detach old rows in answer_user
table (sync
= detach
+ attach
again)
class Question extends Model
{
public function user()
{
//The question should belong to a user.
}
public function answers()
{
//If you use hasMany, then the method should be plural nouns
return $this->hasMany('App\Answer');
}
}
class Answer extends Model
{
//One answer should belong to one question and one 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 you want to use many to many relationship, you can imagine that one question belongs to many tags, and one tag has many questions. Then you 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 you want to have some relationships, you should define it in all tables. Sorry because of my English.
Upvotes: 1