Home » Php » Eloquent one-to-one relationship, in which model should be the hasOne?

Eloquent one-to-one relationship, in which model should be the hasOne?

Posted by: admin September 25, 2018 Leave a comment

Questions:

I have a context where a user can do registrations in conferences. And the registrations can be free or paid depending on the ticket types selected by the user that did the registration.

Doubt 1: But so there should be a 1 to 1 relationship between Registration and Payment. My doubt is if the “hasOne” should be in the Registration model or in the Payment model? Or it is the same? And where is necessary to add the fk? In the the create_payments_table or “create_registrations_table”, or both?

Doubt 2: Also, there are 2 payment methods available, credit card or references. In the case of references is necessary to store the generated references in the references table. So there should also exist a 1 to 1 relationship between Payment and Reference. But I have the same doubt where the hasOne should be? In the Payment or in the Reference model? And where is necessary to add the fk? In the the create_payments_table or “create_references_table”, or both?

Doubt 1 models:

// Registration Model
class Registration extends Model
    public function payment()
        {
            return $this->hasOne('App\Payment');
        }
    }

// Payment model
class Payment extends Model
{
    public function registration()
    {
        return $this->belongsTo('App\Registration');
    }
}

Doubt 2 models:

// Payment model
class Payment extends Model
{
    public function registration()
    {
        return $this->belongsTo('App\Registration');
    }

    public function reference()
    {
        return $this->hasOne('App\Reference');
    }
}
// Reference model
class Reference extends Model
{
    public function payment()
    {
        return $this->belongsTo('App\Payment');
    }
}
Answers: