devondahon's avatar

HasOne relationship id returns 0 instead of real value

I created a HasOne relationship according to this: https://laravel.com/docs/10.x/eloquent-relationships#one-to-one

When I query $user = User::find(1), I'm getting the phone model with $user->phone, but I can't get the phone id with $user->phone->id, it's always returning 0.

What's wrong with getting the id, what should I do to getit ?

0 likes
7 replies
LaryAI's avatar
Level 58

It's possible that the id column in the phones table is not set as the primary key. In that case, you can specify the foreign key and local key in the relationship definition. For example:

class User extends Model
{
    public function phone()
    {
        return $this->hasOne(Phone::class, 'user_id', 'id');
    }
}

Here, user_id is the foreign key in the phones table that references the id column in the users table.

If this is not the issue, it's possible that the id column in the phones table is not being populated correctly. Check that the id column has a default value of NULL and that it is set to auto-increment.

jaseofspades88's avatar

Can you show us your user model? I assume you haven't added the phone method to it.

devondahon's avatar

@jaseofspades88 Thanks for your answer, it seems to be due to my primary key, not the relationship: I probably have to rewrite my migration with standard auto-increment integer id and the token in a token column instead of id.

> $t = ParticipationAccessToken::first()
= ParticipationAccessToken {#4016
    id: "qwertyuiopasdfghjklzxcvbnm",
    participation_id: 220392,
    revoked: false,
    created_at: "2023-04-13 18:31:59",
    updated_at: "2023-04-13 18:31:59",
  }

> $t->id
= 0
tykus's avatar

@devondahon did you specify that the $keyType should be a String on the Model?

Personally, I would stick to the convention of an unsigned integer for the Primary Key wherever possible

Snapey's avatar
Snapey
Best Answer
Level 122

You have to tell eloquent if you want to use a non-incrementing primary key

Add to your Phone model

public $incrementing=false;
1 like
devondahon's avatar

@Snapey That fixed my issue!! Thanks a lot!! Should I still rewrite my migration for a more standard one ?

Snapey's avatar

@devondahon as long as you have a unique primary key.... always best to stick with conventions though.

Please or to participate in this conversation.