I have two tables in the database, one for phrases and one for users, where a user can have many phrases and that phrase only belongs to one user.
I have populated my database with factory to do some tests, but I have noticed that for some records their relations are not loaded, nor the reverse (Phrases => User ; User => Phrases). This only happens with some registers, which seems quite strange to me.
I have checked how the records that do not load their relation in the database are and they look good, related under a foreign key not null and without problems to make the match in SQL.
Relations
// Phrases
public function User() : BelongsTo {
return $this->belongsTo(User::class, 'user_id');
}
// User
public function Phrases() : HasMany {
return $this->hasMany(Phrase::class, 'user_id', 'id');
}
Query:
App\Models\User::with('Phrases')->where('id','74e21510-b466-4376-8ad5-2950830853fa')->first();
App\Models\Phrase::with('User')->where('id',573)->first();
Note: When calling the models separately (Models that do not load their relations), both exist and are displayed without problems.
What could be wrong? Why does it only happen with some models and not with all?
Laravel 8.x
Given the value that I see in your query for the primary key of the model
user
, I consider that some changes must be generated in said class.For the aforementioned, the Eloquent documentation, in its model conventions section 1 , indicates that:
If the primary key does not have the expected name, which it is,
id
then we must declare a property in said model that helps Eloquent determine it ( at the moment this does not seem to be your situation, but it should be kept in mind if it applies ).If the primary key is not a self-incrementing integer then we must declare a property on the class that indicates it like this:
Finally, if the primary key is based on a data type other than an integer, then you must also indicate it in this way in the class:
References