I have 2 models: TopHistory and User
I using UUID for id column in User table, and user_id column in TopHistory.
In TopHistory model. I have create a relationship method
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
I have 4 user and 4 history records. Each history record, I use $user->id itself to add the user_id field.
And I try return TopHistory::with('user')->get().
But only 3 record return user data. Just have one record return null.
I am sure the user_id field values of the 4 history records all exist user.
Someone please help me solve this. Thanks
As @vincent15000 mentioned, what does your actual database have stored? Is it possible that when one of the records was being saved, the ID wasn't stored (e.g. because you didn't have it in your $fillable array at the time)?
@vincent15000@nexxai Sorry for late reply, sir. I have checked in Workbench. The user_id field in all history records has been populated. I tried copying them and writing a search query in the user table, of course the results returned.
@JussiMannisto You're right I just re-read the post again and the relation is created in the Tophistory model that has the clumn user_id therefor foreignkey should be user_id and not id
If you would like a model to use a UUID key instead of an auto-incrementing integer key, you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model. Of course, you should ensure that the model has a UUID equivalent primary key column
Have you added this trait?
Also, you should not specify the foreign and primary keys in the relationship since there is a very good chance of getting them the wrong way around. If you are using conventions of id for primary key and user_id for the fk pointing to the user model then don't specify the keys.
public function user() {
return $this->belongsTo(User::class);
}