devondahon's avatar

HasOne through two ids

In my Participation model, I have this:

    public function invitation(): hasOne
    {
        return $this->hasOne(Invitation::class)->where([
          ['user_id', $this->user_id],
          ['survey_id', $this->survey_id]
        ]);
    }

which returns : local.ERROR: SQLSTATE[42703]: Undefined column: 7 ERROR: column invitations.participation_id does not exist

Participation and Invitation models both have user_id and survey_id, and there's always a participation for an invitation. How can I change this code to get the invitation corresponding to a participation, and be able to load like this ->with('invitation') ?

0 likes
1 reply
vincent15000's avatar

With a has one relationship, Laravel is looking for a participation_id field in the invitations table. It seems that the invitations table doesn't have any participation_id field.

Or perhaps you have named it differently ? If yes, you need to specify its name within the relationship definition.

$this->hasOne(Invitation::class, 'custom_name_for_foreign_id')->...

https://laravel.com/docs/10.x/eloquent-relationships#one-to-one

Please or to participate in this conversation.