Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a has many relationship tables at the same time in laravel

I am using PHP Laravel Framework.I have 1 to M relationship tables order and products.

ORDER TABLE - orderid <--autoincrement primary key
                          - orderdate
                          - Name

PRODUCTS TABLE - productid <--autoincrement primary key
                              - orderid <--foreign key reference to order table
                              - productName
                              - price
My models are as below -->
Order Model :

class Order extends Eloquent 
{

    protected $table = 'order';

    public function products()
    {
        return $this->hasMany('Products','orderid');
    }

}

Products Model :

class Products extends Eloquent 
{
    protected $table = 'products';
}

I have a form where I am taking the order date,name of the customer and the products details that can be more than one products.User can have one or many products in one order.
So now i have to insert details about both the tables in one go .
I read this doc http://laravel.com/docs/eloquent#inserting-related-models
they have given this below code for inserting related models -->

$comments = array(
    new Comment(array('message' => 'A new comment.')),
    new Comment(array('message' => 'Another comment.')),
    new Comment(array('message' => 'The latest comment.'))
);

$post = Post::find(1);

$post->comments()->saveMany($comments);

But here they know the id to find from the parent table but in my case I have to insert details in the Order table and then the details about the products in the Products table for the order which was inserted just before . Problem is how to find the newly inserted orderid ? I am using autoincrement for orderid field in the Order table.

like image 599
Vishal Nair Avatar asked Jun 30 '14 17:06

Vishal Nair


2 Answers

Simply:

$order = new Order;
... // assign some properties
$order->save();

$products = [new Product(...), new Product(...)];

$order->products()->saveMany($products);

And set the protected $primaryKey on the models, like Zwacky already said.

Now, I doubt it's the relation you want. That means every product exists only in the context of a single order. I think this should be many to many, but that's your call.

like image 78
Jarek Tkaczyk Avatar answered Oct 05 '22 23:10

Jarek Tkaczyk


if you create model by model you shouldn't have any problems. if you save() the model, its primary key id property will be set with the last inserted id automatically. here some idea:

$products = [];
foreach (['product A', 'product B'] as $name) {
    $product = new Product;
    $product->name = $name;
    $product->price = 15;
    $product->save();
    // $product->id will be set after save()
    array_push($products, $product);
}

$someOrder->products()->saveMany($products);
like image 41
Simon Wicki Avatar answered Oct 05 '22 23:10

Simon Wicki