【问题标题】:Call to a member function save() on null in Laravel test在 Laravel 测试中调用 null 上的成员函数 save()
【发布时间】:2020-06-28 03:15:42
【问题描述】:

我正在上 Codecourse 上的 Laravel 课程。到目前为止,我有一个类别模型:

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 版本之间存在一些差异,但这似乎更基本。

【问题讨论】:

标签: php laravel


【解决方案1】:

您的关系方法中缺少返回:

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

【讨论】:

  • 当然是简单而愚蠢的事情,就像我一样:|谢谢!
猜你喜欢
  • 2016-06-29
  • 1970-01-01
  • 2017-07-19
  • 2017-05-22
  • 2021-09-08
  • 1970-01-01
  • 2021-11-05
  • 2020-03-01
  • 2016-09-04
相关资源
最近更新 更多