wlin wlin - 7 months ago 79
PHP Question

Laravel 5 Many to Many insert Custom Pivot Cell

I can't find any on the official doc.

I need to insert

$product_count
in my
invoice_product
pivot table

$product_ids = [1,2,3];
$product_count = [1,1,1];

$invoice->product()->attach($product_ids, $product_count); // don't work



SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into
invoice_product
(
0
,
created_at
,
invoice_id
,
product_id
,
updated_at
,
1
) values (2, 2016-04-26 15:33:57, 437, 1500125, 2016-04-26 15:33:57, 1), (2, 2016-04-26 15:33:57, 437, 5121100, 2016-04-26 15:33:57, 1))


It is expecting a string in the 2nd arg, how should I go about it.

$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(): Parameter mismatch, pattern is a string while replacement is an array


UPDATE so when i tried

$invoice->product()->attach($product_ids, array('product_count'=>2));


this will put the static 2 in all of the invoice_product, how do I insert it as array b/c each product count need to be different?

Answer

Assuming your database field is : count

invoice_product table

invoice_id
product_id
count

Product Model

public function invoices() {
    return $this->belongsToMany('App\Invoice')->withPivot('count');
}

Invoice Model

public function products() {
    return $this->belongsToMany('App\Product')->withPivot('count');
}

In your controller

//$invoice->products()->attach([1 => ['count' => 1]]);

In general cases, you must attach :

[
$productId1 => ['count' => $countId1],
$productId2 => ['count' => $countId2],
]

In your case, you have to do something like :

$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);
Comments