Laravel更新数据透视表(多对多关系)

时间:2017-09-13 22:14:21

标签: laravel laravel-5

我有表名为users,questions,answers和answer_user的表。我可以使用$ user-> answers方法从表中获取数据但我无法弄清楚如果不存在则如何更新或插入。 (answer_user表)

用户表:

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

1 个答案:

答案 0 :(得分:0)

您可以看到参考here。当您使用attach时,它将在answer_user表中创建一些新行。如果您不再需要此行,则可以detach。或者,当您想要添加新行并在sync表格中分隔旧行(answer_user = sync + detach再次)时,您可以使用attach

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

如果你想使用多对多的关系,你可以想象一个问题属于许多标签,一个标签有很多问题。然后你可以定义它。

class Tag extends Model
{
    public function questions()
    {
        return $this->belongsToMany('App\Question');
    }
}

class Question extends Model
{
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}

如果您想要有一些关系,您应该在所有表中定义它。 抱歉,因为我的英语。