I am developing a database for giveaways. I have two main tables: participants
and giveaways
with an N:N relationship since a participant can participate to one or more giveaways and a giveaway can have one or more participants. My (simplified) table structure is the following:
giveaways
----------------------
uuid name
participant_giveaway
----------------------
id giveaway_uuid fiscal_code
participants
----------------------
fiscal_code first_name last_name
Now, I have followed the docs for Laravel 11 but the relationship gives me wrong results. For instance, I have 4 participants for a giveaway and when I try to retrieve them with Giveaway::find($uuid)->participants
, it returns 2 random participants that are linked to another giveaway.
This is my Giveaway
model.
<?php
namespace AppModels;
use IlluminateDatabaseEloquentConcernsHasUuids;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsToMany;
use IlluminateDatabaseEloquentRelationsHasMany;
use IlluminateSupportCollection;
use SpatieMediaLibraryHasMedia;
use SpatieMediaLibraryInteractsWithMedia;
class Giveaway extends Model implements HasMedia
{
use HasFactory, InteractsWithMedia, HasUuids;
protected $primaryKey = 'uuid';
protected $fillable = [
'name',
'terms_and_conditions',
'privacy_policy',
'date_start',
'date_end'
];
protected $casts = [
'date_start' => 'datetime',
'date_end' => 'datetime',
];
public function participants(): BelongsToMany
{
return $this->belongsToMany(Participant::class, 'participant_giveaway', 'giveaway_uuid', 'fiscal_code')
->withPivot('drawn', 'code', 'expiration_date', 'status', 'created_at')->withTimestamps();
}
public function drawableParticipants(): Collection
{
return $this->participants()->where('drawn', 0)->get()->pluck('participant');
}
}
This is my Participant
model.
<?php
namespace AppModels;
use DatabaseFactoriesParticipantFactory;
use IlluminateDatabaseEloquentFactoriesFactory;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsToMany;
use IlluminateDatabaseEloquentRelationsHasMany;
use IlluminateDatabaseEloquentRelationsHasOne;
use IlluminateSupportCollection;
class Participant extends Model
{
use HasFactory;
protected $fillable = [
'name',
'date_start',
'date_end'
];
public function giveaways(): BelongsToMany
{
return $this->BelongsToMany(Giveaway::class, 'participant_giveaway', 'fiscal_code', 'giveaway_uuid')
->withPivot('drawn', 'code', 'expiration_date', 'status', 'created_at')->withTimestamps();
}
}