When I try to test two of my models with factories there’s an error message that says I’m no setting “type” value.
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: comment_votes.type (Connection: sqlite, SQL: insert into "comment_votes" ("comment_id", "user_id") values (1, 18), (2, 18), (3, 18), (4, 18), (5, 18))
In my comment_votes
table have comment_id
, user_id
and type
columns, all of these non nullable.
Schema::create('comment_votes', function (Blueprint $table) {
$table->id();
$table->foreignId('comment_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('type');
$table->timestamps();
});
I tried to test the relationship with Pest using the code below
test('BelongsToMany relationship works', function () {
$user = User::factory()
->has(CommentVote::factory()->count(5), 'votedComments')
->create();
assertCount(5, $user->votedComments);
});
My User model looks like this:
class User extends Authenticatable
{
// Rest of the model...
/**
* Get the comments where the user has voted.
*/
public function votedComments(): BelongsToMany
{
return $this->belongsToMany(Comment::class, CommentVote::class);
}
}
My CommentVote model looks like this:
class CommentVote extends Model
{
use HasFactory;
protected $fillable = [
'comment_id',
'user_id',
'type', // Notice that is included
];
protected static function newFactory(): Factory
{
return CommentVoteFactory::new();
}
protected function casts(): array
{
return [
'type' => CommentVoteType::class,
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function comment(): BelongsTo
{
return $this->belongsTo(Comment::class);
}
}
My CommentVoteFactory looks like this:
class CommentVoteFactory extends Factory
{
protected $model = CommentVote::class;
public function definition(): array
{
return [
'comment_id' => Comment::factory(),
'user_id' => User::factory(),
'type' => 'positive', // Notice that is included
];
}
}