Sayalic
Sayalic

Reputation: 7650

Why the name convention of Laravel relationships so weird?

I have three tables:

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:

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?

Upvotes: 0

Views: 162

Answers (2)

Raymond Cheng
Raymond Cheng

Reputation: 2495

You don't need define a model for pivot table,just add withPivot

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

Then you can retrieve book states from model pivot

Upvotes: 1

Can Vural
Can Vural

Reputation: 2067

Generally you don't need a model for pivot tables. You can define the inverse of the relationship. And if you want to store extra data in pivot table maybe you can check withPivot method. Or explain what are you trying to do.

But if you want to create a model, you need to specify your table name in your model manually. Because Laravel doesn't know if its a pivot table or normal table. It just tries to guess the table name by making it plural.

Upvotes: 1

Related Questions