Answer the question
In order to leave comments, you need to log in
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');
}
<?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()
];
}
}
<?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,
];
}
}
$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))
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' -> User::factory(),
'occupation' => 'Occupation',
'description' => 'Description',
'reputation' => 0,
];
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question