Home > OS >  Problem : randomly generate data from a table with a factory
Problem : randomly generate data from a table with a factory

Time:10-06

I want take a random id already existing from my garage table, so i have a problem.

<?php

namespace Database\Factories;

use App\Models\Car;
use App\Models\Garage;
use Illuminate\Database\Eloquent\Factories\Factory;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'release_year' => $this->faker->year(),
            'garage_id' => Garage::inRandomOrder('id')->first('id'),
            'created_at' => now()
        ];
    }
}

The Problème is :

PHP Deprecated: Since fakerphp/faker 1.14: Accessing property "name" is deprecated, use "name()" instead. in /data/www-local/web/lara_sites/swan-formation-laravel/vendor/symfony/deprecation-contracts/function.php on line 25 PHP Deprecated: Since fakerphp/faker 1.14: Accessing property "year" is deprecated, use "year()" instead. in /data/www-local/web/lara_sites/swan-formation-laravel/vendor/symfony/deprecation-contracts/function.php on line 25 Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'garage_id' cannot be null (SQL: insert into cars (name, release_year, garage_id, created_at, updated_at) values (Alf Bayer, 1994, ?, 2021-10-05 16:21:19, 2021-10-05 16:21:19))'

CodePudding user response:

The inRandomOrder method may be used to sort the query results randomly. it has no argument, you can use it like:

 'garage_id' => Garage::inRandomOrder()->first()->id,

you should make sure of that your garages table is not empty.

CodePudding user response:

You can try this

'garage_id' => $this->faker->randomElement(Garage::query()->get('id')),

CodePudding user response:

Ok I found out, that was it, it's just that my tinker was bugging

  • Related