Home > Software engineering >  Eloquent - Multiple belongsTo?
Eloquent - Multiple belongsTo?

Time:11-28

I can't seem to find a straight answer on whether Eloquent models can have multiple belongsTo relationships.

Just in terms of normalized DB relationships, this is perfectly valid. Let's take the hypothetical example of a CMS page that belongs to one and only one author, and also belongs to one and only one category. The author and category have no relation to or bearing on one another. In the DB, we'd simply expect a page to have an author_id and a category_id field, each with a foreign key to a different table.

Seems like it would be valid to do:

class Page extends Model
{
    public function author()
    {
        return $this->belongsTo(Author::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

The scenario seems valid ... EXCEPT that this seems to break the convention and automagic of the associate and dissociate methods, which expect there to be only a single "belongs to" relationship.

So is it proper to use multiple belongsTo relationships on the same model? And if not, how would you express a common scenario like this instead? (I should note right off the bat that this is not the same scenario as polymorphic relationships, where one model belongs to one other, which may be this OR that type.)

CodePudding user response:

Eloquent Model's can have multiple same relationship. Means you can have belongsToMany() as many as you need, you can have a belongsTo(), hasOne(), hasMany() etc. It will not affect the other relationship since they have a different method name. which is the main identification for the relationship.

The scenario seems valid ... EXCEPT that this seems to break the convention and automagic of the associate and dissociate methods, which expect there to be only a single "belongs to" relationship.

If you understand the documentation Updating BelongsTo Relationship you will use the associate() or dissociate() after the relationship method. There's no "except there to be only a single belongs to relationship". in the documentation.

$page->author()->dissociate(); // it will set the "author_id" on the page as null and will not affect the `category()` at all.

$page->category()->associate($category); // it will add a the "category_id" of the given category to the page and will not affect the `author()` at all.
  • Related