vendredi 23 septembre 2016

Why the name convention of Laravel relationships so weird?

I have three tables:

  • users
    • columns: id, name
  • books
    • columns: id, name
  • book_user:
    • columns: user_id, book_id, state(not read yet, reading, read already)

I intended to user book_user as many-to-many relation table, so I follow the name convention from doc:

To define this relationship, three database tables are needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

I wrote code:

class User extends Model
{
    public function books()
    {
        return $this->belongsToMany('App\Book');
    }
}

, and I can retrieve the books which related to the user by call user->books().

That works well, but when I try to retrieve the state of the book which related to a user, I create model:

class BookUser extends Model
{
    //
}

When I use this Model, it claims:

Base table or view not found: 1146 Table 'myapp.book_users' doesn't exist

Conclusion:

  • the name convention of a table which can be used as many-to-many is <singular_noun>_<singular_noun> (such as book_user).
  • the name convention of table with multiple words which mapping to a Model is <singular_noun>_<plural_noun> (such as book_users).

I know I can set the table name manually which a model mappings to, but I just wonder:

Does that conflict is a design flaw or just I'm doing wrong in designing tables and models?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire