2017-09-13 129 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