Yahya Uddin
Yahya Uddin

Reputation: 28841

How to create a model for this relationship in Laravel 5?

I have the following schema:

Modules
=======
id: PK
current_revision: FK to Revisions.Id, nullable

Revisions
=========
id: PK

The current_revision field either references to a single revision id or set to null.

My question is how do I properly model this relationship in Laravel.

Here's how I did it so far:

class Module extends Model
{
    public function current_revision()
    {
        return $this->belongsTo(Revision::class, 'current_revision');
    }

}

However, I did not do the inverse in the revision model, as there can be revisions with no module assigned to it.

Is this the correct way to model this relationship?

Also why does the following $module->current_revision not output a collection of revisions? Instead it outputs the contents of the field.

However it's worth mentioning the following works fine: $module->current_revision()->getResults()

Upvotes: 1

Views: 61

Answers (1)

Daniel Castro
Daniel Castro

Reputation: 633

About your current relationship:

Since current_revision points to only one record on the revisions table, you can expect your relationship to return a single Revision model, and not a collection.

The reason you are getting the contents of the field and not the model, is that your field and relationship share the same name. So, when you ask for $model->current_revision, Laravel gives you the value of that field on the database.

The easiest way to solve this would be to rename either the database column or the relationship name. I usually append _id to foreign key columns so that is never a problem.

About the inverse relationship:

You can define the relationship the same way, even though the column is nullable. If there aren't any modules related to one revision, $revision->module (for example) will just return null.

Upvotes: 1

Related Questions