Laravel 5以其他属性雄辩多对多的枢轴

时间:2016-06-22 19:48:40

标签: php laravel-5 eloquent

我有两个表格invoicesitems有多对多的关系,我的角色qnty还有一个额外的属性,如何为qnty分配一个值通过invoice模型使用雄辩的? 我正在尝试使用种子进行测试

我的代码

模型

 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');
    }
 }

数据透视表

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);
    });

这就是我想在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;
          }     
    }
}

0 个答案:

没有答案