2017-09-13 125 views
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'); 
    } 
} 

回答

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

如果你想有一些关系,你应该在所有表中定义它。 对不起,因为我的英语。

+0

它为什么不只是更新而不是添加新行? – Dejavu

+0

如果你想在2表之间有任何关系,你必须添加新的行。或者你可以在关系存在的时候更新它 –

+0

“关系存在时更新”是什么意思?以及我认为我已经拥有了? – Dejavu