簡體   English   中英

在 Laravel 測試中調用 null 上的成員 function save()

[英]Call to a member function save() on null in Laravel test

我正在 Codecourse 上學習 Laravel 課程。 到目前為止,我有一個類別 model:

class Category extends Model
{   
    protected $fillable = [
        'name',
        'slug',
        'order'
    ];

    public function scopeParents(Builder $builder){
        $builder->whereNull('parent_id');
    }

    public function scopeOrder(Builder $builder, $direction = 'asc'){
        $builder->orderBy('order', $direction);
    }

    public function children(){
        $this->hasMany(Category::class, 'parent_id', 'id');
    }
}

一個工廠:

$factory->define(Category::class, function (Faker $faker) {
    return [
        'name' => $name = $faker->unique()->name,
        'slug' => Str::slug($name)
    ];
});

和一個測試

public function test_it_has_many_children()
    {
        $category = factory(Category::class)->create();

        $category->children()->save(
            factory(Category::class)->create()
        );

        $this->assertInstanceOf(Category::class, $category->children->first());
    }

但是,當我運行測試時,我得到:

Call to a member function save() on null

  at tests/Unit/Models/Categories/CategoryTest.php:14
    10|     public function test_it_many_children()
    11|     {
    12|         $category = factory(Category::class)->create();
    13| 
  > 14|         $category->children()->save(
    15|             factory(Category::class)->create()
    16|         );
    17| 
    18|         $this->assertInstanceOf(Category::class, $category->children->first());

是什么賦予了? 該課程已有幾年的歷史,因此我認為 Laravel 版本之間存在一些差異,但這似乎更基本一些。

您在關系方法中缺少返回:

public function children()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM