2017-02-22 130 views
0

我需要創建一個將數據寫入關係表的方法。我通過get發送數據,並且需要將它們存儲在我的表中。以下是我現在寫給你的代碼。將數據存儲到一個多對多的表格關係表中Laravel

public function store(Request $request){ 

     $campanha = Campanha::find($request->campanha); 

     foreach ($request->chksintese as $key => $value) { 
      $campanha->sinteses()->attach($value); 

     } 

     return redirect('sintese-campanha'); 
    } 

我的請求是這樣說的:

array:2 [▼ 
    "campanha" => "26" 
    "chksintese" => array:5 [▼ 
    0 => "92" 
    1 => "86" 
    2 => "1" 
    3 => "9" 
    4 => "13" 
    ] 
] 

在我的模型有關係的方法:

public function sinteses(){ 
     return $this->belongsToMany(Sintese::class); 
} 

而且

public function campanhas(){ 
     return $this->belongsToMany(Campanha::class); 
} 

我知道這是非常基本的,但我現在從laravel開始。我希望有人能幫幫忙。

我真的剛開了一個錯誤:

QueryException in Connection.php line 769: 
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "campanha_sintese" does not exist 
LINE 1: insert into "campanha_sintese" ("campanha_id", "sintese_id")... 
^ (SQL: insert into "campanha_sintese" ("campanha_id", "sintese_id") values (31, 13)) 

我的遷移代碼爲我relashionship表

public function up() 
{ 
    Schema::create('callcenter.campanha_sintese', function(Blueprint $table) { 

     $table->integer('sintese_id')->unsigned; 
     $table->foreign('sintese_id')->references('cod_sintese_conversa')->on('crm.sintese_conversa'); 

     $table->integer('campanha_id')->unsigned; 
     $table->foreign('campanha_id')->references('id_campanha')->on('callcenter.campanha_new'); 

     $table->timestamps(); 
    }); 
} 
+0

好吧,那麼你的問題是什麼?提供的代碼不起作用?你會得到什麼錯誤?你可以更新你的問題 –

+0

是的,我的代碼沒有工作,我接收到這條消息:SQLSTATE [42P01]:未定義表:7錯誤:關係「campanha_sintese」不存在 線1:插入「campanha_sintese」(「campanha_id (SQL:插入「campanha_sintese」(「campanha_id」,「sintese_id」)值(31,13)) –

+0

您必須創建帶有指定字段的數據透視表「campanha_sintese」 –

回答

1

通過你的表,你的關係,以便Laravel知道去哪裏找的關係。

public function sinteses(){ 
    return $this->belongsToMany(Sintese::class, "callcenter.campanha_sintese"); 
} 

public function campanhas(){ 
    return $this->belongsToMany(Campanha::class, "callcenter.campanha_sintese"); 
} 

您可能還需要在您的關係中添加主鍵和外鍵。查看Laravel如何添加這些密鑰的指南。挺容易。

+0

謝謝艾迪,這解決了我的問題 –

相關問題