Skip to content

Morph pivot table name conventions wrong when using MorphPivot model #43800

@DarkGhostHunter

Description

@DarkGhostHunter
  • Laravel Version: 9.25.1
  • PHP Version: 8.1.9
  • Database Driver & Version: N/A

Description:

You can tell a morphToMany or morphedByMany relations to use a Morph Pivot model by using a third parameter as the Model class name. This will also set the pivot table from it.

return $this->morphToMany(Tag::class, 'taggable', Taggable::class).

The problem is that Eloquent tries to find the subscription table, where as it should be subscriptions. This is becase getTable() in a Pivot|MorphPivot model doesn't returns the model plural, but rather the snake-singular.

class Post extends \Illuminate\Database\Eloquent\Model {
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable', Taggable::class);
    }
}

Post::find(1)->tags()->dd();

// "select * from "tags" 
//    inner join "taggable" on "tags"."id" = "taggable"."tag_id" 
//    where 
//        "taggable"."taggable_id" = ? 
//    and 
//        "taggable"."taggable_type" = ?"

Here, the table should be taggables instead of taggable. This would force the developer to, unexplainably, set the table name property in the pivot model.

What it should happen?

If the developer is setting the morph pivot model, it should always use the plural instead of a two-model-junction to guess the table. This shouldn't affect the normal pivot model (for belongs to many).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions