【问题标题】:Laravel many to many relationship errorLaravel 多对多关系错误
【发布时间】:2016-11-24 13:06:14
【问题描述】:

我在PluginsUser 的名称下分别有两个models 和表格。我正在尝试在名为 migrationmigration 中使用名为 pivot tablepivot table 和名为 create_users_plugins_table.phpmany to many relationship

以下是架构:

public function up()
{
    Schema::create('plugin_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('plugins_id');
        $table->json('contents');
        $table->timestamps();
    });
}

User model 中,我有以下关系函数:

public function userplugins(){

    return $this->belongsToMany('App\Plugins')->withPivot('contents');
}

通过以下代码获取行时:

$user = User::findorFail($id);
return $user->userplugins()->first()->contents;

我收到以下错误:

SQLSTATE[42S02]:找不到基表或视图:1146 表“nitsbuilder.plugins_user”不存在(SQL:选择plugins.*、plugins_user.user_idpivot_user_id、@987654338 @.plugins_id as pivot_plugins_id, plugins_user.contents as pivot_contents from plugins inner join plugins_user on plugins.id = plugins_idplugins_id.@987 .user_id = 1 限制 1)

请帮我修复这个错误。

谢谢

【问题讨论】:

  • 希望您已经运行了迁移?你的Plugins 模型中的代码是什么?
  • 就这么简单:plugin_user !== plugins_user 错误准确地告诉你问题所在。您没有定义 plugins_user 而是定义了 plugin_user - 您可以在关系 laravel.com/docs/5.1/eloquent-relationships#many-to-many 中更改引用的表名
  • @ArifulHaque 我已经这样做了。
  • @FrankProvost 感谢您的更新。从我这里来

标签: laravel eloquent many-to-many laravel-5.2


【解决方案1】:

看起来在您的迁移中,您的表名是

`plugin_user` 

但是查询搜索

`plugins_user`

您可能需要使用表名更新您的 Plugin 模型。

【讨论】:

    【解决方案2】:

    问题是您的表的名称。该错误表明它正在寻找 plugins_user 但您的迁移显示 plugin_user 表缺少 s。这可能是由于模型 Plugins 的命名应该是 Plugin

    要么更改表名,要么去https://laravel.com/docs/5.1/eloquent-relationships#many-to-many查看如何更改关系的引用表。

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2021-07-06
      • 2018-02-06
      • 2019-09-22
      • 1970-01-01
      • 2021-10-29
      • 2018-06-15
      • 2018-01-22
      • 2016-02-26
      相关资源
      最近更新 更多