Laravel 8基于类的模型工厂

时间:2020-09-10 11:49:11

标签: laravel laravel-8

我试图弄清楚为什么当我尝试创建我的Player类和dd($this)的工厂时会回来的原因是它没有覆盖模型的状态。同样没有意义的是,它是两个状态的集合。

任何人都可以进一步澄清吗?

$player = Player::factory()->injured()->create();


<?php

namespace Database\Factories;

use App\Enums\PlayerStatus;
use App\Models\Player;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class PlayerFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected string $modelClass = Player::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition(): array
    {
        return [
            'name' => $this->faker->name,
            'height' => $this->faker->numberBetween(60, 95),
            'weight' => $this->faker->numberBetween(180, 500),
            'hometown' => $this->faker->city.', '.$this->faker->state,
            'status' => PlayerStatus::__default,
        ];
    }

    public function injured(): self
    {
        $this->state([
            'status' => PlayerStatus::INJURED,
        ]);

        dd($this);

        $now = now();
        $start = $now->copy()->subDays(2);

        $this->hasEmployments(1, ['started_at' => $start]);

        $this->hasInjuries(1, ['started_at' => $now]);

        return $this;
    }
}


    ^ Database\Factories\PlayerFactory^ {#2650
  #modelClass: "App\Models\Player"
  #model: null
  #count: null
  #states: Illuminate\Support\Collection^ {#2647
    #items: array:2 [
      0 => Closure()^ {#2631
        class: "Illuminate\Database\Eloquent\Factories\Factory"
        this: Database\Factories\PlayerFactory {#2626 …}
        use: {
          $state: []
        }
      }
      1 => Closure()^ {#2646
        class: "Illuminate\Database\Eloquent\Factories\Factory"
        this: Database\Factories\PlayerFactory {#2648 …}
        use: {
          $state: []
        }
      }
    ]
  }
  #has: Illuminate\Support\Collection^ {#2610
    #items: []
  }
  #for: Illuminate\Support\Collection^ {#2640
    #items: []
  }
  #afterMaking: Illuminate\Support\Collection^ {#2455
    #items: []
  }
  #afterCreating: Illuminate\Support\Collection^ {#2453
    #items: []
  }
  #connection: null
  #faker: null
}

1 个答案:

答案 0 :(得分:0)

方法调用:

$this->state([
        'status' => PlayerStatus::INJURED,
]);

不会修改当前对象-它会使用更新的“状态”创建一个新的工厂实例。而这个新工厂应该通过受伤的方法退还。

在这种情况下,一种解决方案是:

public function injured(): self
{
    $injuredPlayer = $this->state([
        'status' => PlayerStatus::INJURED,
    ]);

    $now = now();
    $start = $now->copy()->subDays(2);

    $injuredPlayer->hasEmployments(1, ['started_at' => $start]);

    $injuredPlayer->hasInjuries(1, ['started_at' => $now]);

    return $injuredPlayer;
}