我有两个表格invoices
和items
有多对多的关系,我的角色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;
}
}
}