Laravel 工厂逻辑

Laravel Factory Logic

我有下面的工厂。当我将其设置为创建多个模型时,ID 似乎并没有增加。请帮助我了解如何使此代码正常工作,以便 ID 每次都递增。

<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\PurchaseOrder;
use Faker\Generator as Faker;
use Illuminate\Support\Facades\DB;

$factory->define(PurchaseOrder::class, function (Faker $faker) {

    DB::select(DB::raw('SET FOREIGN_KEY_CHECKS=0'));
    $numberOfLines = rand(1, 5);
    $id = PurchaseOrder::all()->last()->id + 1?? 1;

    for ($i = 0; $i < $numberOfLines; $i++) {
        $line = factory(App\Line::class)->make([
            'purchase_order_id' => $id,
        ]);
        $line->save();
    };

    $lines = App\Line::where('purchase_order_id', $id)->get();
    DB::select(DB::raw('SET FOREIGN_KEY_CHECKS=1'));
    return [
        'total_price_ex_vat' => $lines->sum('price_ex_vat'),
        'total_price_inc_vat' => $lines->sum('price_inc_vat'),
        'revised_total_price_ex_vat' => $lines->sum('revised_price_ex_vat'),
        'revised_total_price_inc_vat' => $lines->sum('revised_price_inc_vat'),
        'deliver_to' => $faker->words(2, true),
        'requested_staff_id' => factory(App\Staff::class)->create()->id ,
        'auth_staff_id' => Null,
        'supplier_id' => factory(App\Supplier::class)->create()->id,
        'rejection_code_id' => Null,
        'status_id' => 1,
        'status_changed_date' => date('Y-m-d'),
        'user_id' => factory(App\User::class)->create()->id,
    ];

});

您有 table PurchaseOrder 依赖于 Lines,而 Lines 依赖于 PurchaseOrder。我相信你应该检查你的数据库设计,因为这看起来很奇怪。

为什么不避免在 PurchaseOrder 中使用 Lines 并使用访问器将其作为属性加载到 PurchaseOrder 模型中?

更多信息:https://laravel.com/docs/5.8/eloquent-mutators#defining-an-accessor