【问题标题】:Why the name convention of Laravel relationships so weird?为什么 Laravel 关系的命名约定如此奇怪?
【发布时间】:2017-02-01 00:17:18
【问题描述】:

我有三张桌子:

  • 用户
    • 列:ID、名称
  • 书籍
    • 列:ID、名称
  • book_user:
    • 列:user_id, book_id, state(not read yet, reading, read already)

我打算将book_user 用作多对多关系表,所以我遵循doc 的命名约定:

要定义这种关系,需要三个数据库表:usersrolesrole_user。 role_user 表由相关模型名称的字母顺序派生而来,包含 user_id 和 role_id 列。

我写了代码:

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

,我可以通过调用user->books()检索与用户相关的书籍。

效果很好,但是当我尝试检索与用户相关的图书状态时,我创建了模型:

class BookUser extends Model
{
    //
}

当我使用这个模型时,它声称:

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

结论:

  • 可以用作多对多的表的命名约定是<singular_noun>_<singular_noun>(例如book_user)。
  • 映射到Model的多词表的命名约定为<singular_noun>_<plural_noun>(如book_users)。

我知道我可以手动设置模型映射到的表名,但我只是想知道:

这种冲突是设计缺陷还是我在设计表格和模型时做错了?

【问题讨论】:

  • 一个用户可以有很多本书,所以你的关系应该是 hasManyuser->book 更改 return $this->belongsToMany('App\Book');return $this->hasMany('App\Book'); 并在 App\Book 模型上创建反向关联,你有 $this->belongsTo('App\User') .

标签: php laravel laravel-5


【解决方案1】:

您不需要为数据透视表定义模型,只需添加 withPivot

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

然后你可以从模型数据中检索书籍状态

【讨论】:

    【解决方案2】:

    通常您不需要数据透视表模型。您可以定义关系的倒数。如果你想在数据透视表中存储额外的数据,也许你可以检查withPivot 方法。或者解释一下你想做什么。

    但是如果你想创建一个模型,你需要在你的模型中手动指定你的表名。因为 Laravel 不知道它是数据透视表还是普通表。它只是试图通过使其复数来猜测表名。

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多