Laravel 工厂没有返回正确的对象数据

Seb*_*ond 3 php phpunit factory laravel

我在 Laravel 5.7 中有以下工厂,在调用它时没有返回任何内容:

<?php

use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Model;

$factory->define(App\Record::class, function (Faker $faker) {
    return [
        "name" => $faker->name,
    ];
});
Run Code Online (Sandbox Code Playgroud)

而我的模型是:

<?php
namespace App;
use App\Product;
use Illuminate\Database\Eloquent\Model;

class Record extends Model
{
    protected $table = "records";

    protected $fillable = ["name"];

    function __construct()
    {
        parent::__construct();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里调用工厂:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;

use App;
use App\Product;
use App\Record;
use App\User;

class RecordTest extends TestCase
{
    use RefreshDatabase;
    use WithoutMiddleware;

    /** @test */
    public function when_record_page_for_existing_record_is_accessed_then_a_product_is_displayed()
    {
        //$record = factory(App\Record::class)->make();
        $record = factory(App\Record::class)->create();
       echo "\n\n$record->name\n\n";

    }
}
Run Code Online (Sandbox Code Playgroud)

打印时

$record->name
Run Code Online (Sandbox Code Playgroud)

我什么也没得到,不为空,没有空字符串,什么都没有。似乎是什么问题?如果我将工厂生成的任何内容保存到变量中而不是立即返回它,我可以看到正在填充该名称,但是返回后什么也没有发生,它就消失了

Jos*_*ber 11

这段代码是有问题的部分:

function __construct()
{
    parent::__construct();
}
Run Code Online (Sandbox Code Playgroud)

您没有将属性传递给父构造函数。Eloquent 在构造函数中接受模型的属性,但您的覆盖构造函数不接受它们,也不将它们传递给父级。

改成这样:

function __construct(array $attributes = [])
{
    parent::__construct($attributes);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您正在覆盖 Eloquent 的构造函数,但您没有在其中做任何事情。您确定要覆盖它吗?

  • 正确,但“$attributes”默认为空数组。方法签名是“public function __construct(array $attributes = [])” (3认同)