Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel attach with extra field

Tags:

laravel

pivot

I have 3 tables, products, images and product_image. The 3rd one is a pivoting table. Other than product_id and image_id in product_image table, I also have 2 extra fields in this pivoting table: position and type, now for an existing product model A, how do I attach an image to A and at the same time set up its position and type value in that pivoting record? Thanks.

like image 724
dulan Avatar asked Oct 15 '14 00:10

dulan


1 Answers

You may try something like this:

$product = Product::find(1);
// if you need also to save the image
$image = new Image(array('foo' => 'bar'));
$product->images()->save($image,array('position'=>'foo', 'type'=>'bar' ));
// if you know image id
$product->images()->attach([$imageId => ['position'=>'foo', 'type'=>'bar']]);
like image 108
Razor Avatar answered Sep 29 '22 02:09

Razor