A
A
Alexey Sklyarov2020-10-26 20:24:29
Laravel
Alexey Sklyarov, 2020-10-26 20:24:29

What is the correct way to link two models when testing?

I'm trying to test the created User model, which is associated with the UserMeta model like this:

public function meta()
    {
      return $this->hasOne(Usermeta::class, 'user_id');
    }


I create two factories:

UserFactory.php

<?php

namespace Database\Factories;

use App\Models\User;
use App\Models\UserMeta;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
            'meta' => UserMeta::factory()
        ];
    }
}


UserMetaFactory.php

<?php

namespace Database\Factories;

use App\Models\UserMeta;
use App\Models\User;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'occupation' => 'Occupation',
            'description' => 'Description',
            'reputation' => 0,
        ];
    }
}


When I run this code $user = User::factory()->create();in a test, I get an error:
SQLSTATE[23502]: Not null violation: 7 ОШИБКА: нулевое значение в столбце "user_id" нарушает ограничение NOT NULL DETAIL: Ошибочная строка содержит (null, Occupation, Description, 0, 2020-10-26 14:55:47, 2020-10-26 14:55:47). (SQL: insert into "users_meta" ("occupation", "description", "reputation", "updated_at", "created_at") values (Occupation, Description, 0, 2020-10-26 14:55:47, 2020-10-26 14:55:47))

It is clear that the problem is that I do not pass the user_id when I create the UserMeta entry, but why does this problem occur if I point to the UserMeta in the UserFactory? Saw an example for a definition for UserMeta (in my case):
/**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'user_id' -> User::factory(),
            'occupation' => 'Occupation',
            'description' => 'Description',
            'reputation' => 0,
        ];
    }

But at startup I get an error like out of memory. How do two models properly link in Laravel 8?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HabrDima20, 2020-10-28
@HabrDima20

'user_id'=>\App\User::all()->random()->id,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question