基于ID插入多个项目 - Laravel

I have two tables products and shipments and the pivot table product_shipment with fields product_id and shipment_no. In the pivot table, there can be a shipment number eg. #4562 that contains 2 or more products. This is something i want to achieve.

Now this is how my codes works. When i select a product hammer, i am able to retrieve the id of hammer. When i select the id of another product screwdrivers, it replaces the id of hammer instead of storing both.

After inserting my data, i expect something of this sought in my pivot table

Products Table

 product_id   name
    1         hammer
    2         screwdriver

Shipments Table

shipment_no    courrier        
 4562          MaerskLine

product_shipment - Pivot

   shipment_no     product_no
     4562             1
     4562             2

This is where my i select my product checkbox

HTML

 <input onclick="return productSelected(this)" type="checkbox"
 id="{!! $product->id !!}" name="{!! $product->name !!}" /> 

How i select and retrieve my product id when i select a checkbox

JS

  function productSelected(product)
{

    $(".panel").append(
    '<input type="text"  value='+product.id+'   " id="product_id"  name="product_id" />'

}

How i save data into my database

Controller

$product_id = Input::get('product_id');
        $product_selected = Product::all()->where('id',$product_id)->first();

        $shipment_details = new Shipment(array(
            'shipment_no' => $request->get('shipment_no'),
            'courrier' => $request->get('courrier'),


        ));

        $product_id->shipments()->save($shipment_details);   

Shipment Model

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

Product Model

public function shipments()
    {
        return $this->belongsToMany('App\Shipment')
        ->withTimestamps();
    }

How can i get all the id's of the products i select and also have it look like what i have in my pivot table? Thanks for your help

查看全部
doufuxing8691
doufuxing8691
2017/10/28 20:26
  • laravel
  • php
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复