Batmannn
Batmannn

Reputation: 237

Insert in many to many relation laravel 5

I have 2 models:

class Order extends Model
{
    protected $fillable = ['user_id','name','surname','fathers_name','phone_number','city','post_office','comment'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

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

}

class Product extends Model
{

    public function order()
    {
        return $this->belongsToMany('App\Order', 'order_product');
    }

    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

3 tables:

product:
id
name
...

order_product:
id
order_id
prod_id
qty
...

order
id
city
phone
...

and 2 arrays of data: $data = $request->except('_token','submit'); - information about client $order_content - array with info about products in cart

So, the question is how to insert all this data in DB? I tried to read about many to many insertion: sync, attach, etc.. but understood nothing :c

Upvotes: 1

Views: 2310

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Imagine you have a product with id 1. And an order with id 1. The product is part of the order, so you have to attach them. You do

$product = Product::find(1);
$order = Order::find(1);
$order->products()->attach($order->id);

However, in your case, your pivot table has more data, like 'qty'. Then you do,

$order->product()->attach($order->id, ['qty' => 2]);

So far, we were only attaching a single product to an order. If you want to attach many products simultaneously, you do:

$order->products()->sync([
    $product->id => ['qty' => 1],
    $product2->id => ['qty' => 3]
]);

I hope this helps understand better. I recommend you read the doc again and again until it makes sense.

Upvotes: 2

Related Questions