mercredi 22 juin 2016

Laravel 5 Eloquent many to many pivot with additional attribute

I have two tables invoices and items with many to many relationship and I have an additional attribute to their pivot qnty, How do I assign a value to qnty through invoice model using eloquent? I am trying to use seeding for testing

My code

Models

 class Item extends Model
 {
      public function invoices()
   {
    return $this>belongsToMany('app\Invoice','invoice_item','item_id','invoice_id')->withPivot('qnty','price');
   }
 }
 class Invoice extends Model
 {
    public function items()
    {
      return $this->belongsToMany('app\Item','invoice_item','invoice_id','item_id')->withPivot('qnty','price');
    }
 }

The pivot table

Schema::create('invoice_item', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('invoice_id')->unsigned();
    $table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
    $table->integer('item_id')->unsigned();
    $table->foreign('item_id')->references('id')->on('items');
    table->integer('qnty')->unsigned();
    $table->double('price', 10, 2);
    });

And this what I am trying to do in the InvoiceTableSeeder

 public function run()
{   $total="";
    DB::table('invoices')->delete();
     $faker = Faker::create();
    $limit =5;
    for ($i=0; $i < $limit ; $i++) 
    {
        $customer = Customer::all()->random(1);
        $user = User::all()->random(1);
        $invoice =  Invoice::create([
            'invoice No' => $faker->unique()->ean8,
            'customer_id' => $customer->id,
            'User_id'=> $user->id,
            ]);
        for ($x=0; $x <10 ; $x++) { 
            $item = Item::all()->random(1);
            $invoice->items()->attach($item->id);
            $qnt= $invoice->items()->pivot->qnty($faker->numberBetween($min=1,$max=10));
            $total += $item->uniteprice *$qnt;
          }
          $invoice->total = $total;
          $paid= $invoice->paid= $faker->numberBetween($min=0,$max=$total);
          $remain= $invoice->remain= $total-$paid;
          if ($remain>0) {
            $invoice->pending = true;
            $customer->account += $remain;  
          }else{
            $invoice->pending = false;
          }     
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire