Php Laravel 5多对多插入自定义枢轴单元
我在官方文件上找不到 我需要在我的Php Laravel 5多对多插入自定义枢轴单元,php,laravel,Php,Laravel,我在官方文件上找不到 我需要在我的invoice\u product透视表中插入$product\u count $product_ids = [1,2,3]; $product_count = [1,1,1]; $invoice->product()->attach($product_ids, $product_count); // don't work SQLSTATE[42S22]:未找到列:1054“字段列表”中的未知列“0”(SQL:插入invoice\u
invoice\u product
透视表中插入$product\u count
$product_ids = [1,2,3];
$product_count = [1,1,1];
$invoice->product()->attach($product_ids, $product_count); // don't work
SQLSTATE[42S22]:未找到列:1054“字段列表”中的未知列“0”(SQL:插入invoice\u product
(0
,created\u at
,invoice\u id
,updated\u at
,1
)值(2,2016-04-26 15:33:574371500125,2016-04-26 15:33:57,1),(2,2016-04-26 15:33:5743751210012016-04-26 15:33:57,1))
它在第二个参数中需要一个字符串,我应该如何处理它
$product_ids = [1,2,3];
$product_count = [array('product_count'=>2), array('product_count'=>3), array('product_count'=>4)];
$invoice->product()->attach($product_ids, $product_count); // don't work
preg_replace():参数不匹配,模式为字符串,而替换为数组
所以当我尝试
$invoice->product()->attach($product_ids, array('product_count'=>2));
这将在所有发票产品中放置静态2,如何将其作为数组b/c插入每个产品计数需要不同?因此,显然我需要将第一个参数作为与列名称匹配的关联数组
$product_ids = [];
$product_count = [];
foreach($products as $product) {
array_push($product_ids, array('product_id'=>$product->id, 'product_count'=>$product->product_count));
}
$invoice->product()->attach($product_ids);
假设数据库字段为:
count
发票\产品表
invoice_id
product_id
count
产品型号
public function invoices() {
return $this->belongsToMany('App\Invoice')->withPivot('count');
}
public function products() {
return $this->belongsToMany('App\Product')->withPivot('count');
}
发票型号
public function invoices() {
return $this->belongsToMany('App\Invoice')->withPivot('count');
}
public function products() {
return $this->belongsToMany('App\Product')->withPivot('count');
}
在控制器中
//$invoice->products()->attach([1 => ['count' => 1]]);
在一般情况下,您必须附上:
[
$productId1 => ['count' => $countId1],
$productId2 => ['count' => $countId2],
]
在您的情况下,您必须执行以下操作:
$product_ids = [1,2,3];
$product_count = [1,1,1];
$attachements = [];
foreach ($product_ids as $index => $productId) {
$attachements[$productId] = ['count' => $product_count[$index]];
}
$invoice->products()->attach($attachements);