2017-02-22 122 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

谢谢艾迪,这解决了我的问题 –

相关问题