Laravel 多对多关系错误

Laravel many to many relationship error

我在 PluginsUser 的名称下有两个 models 和表格。我正在尝试让 many to many relationshipcreate_users_plugins_table.php 中有一个 pivot table 名为 plugin_usermigration

架构如下:

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]: Base table or view not found: 1146 Table 'nitsbuilder.plugins_user' doesn't exist (SQL: select plugins.*, plugins_user.user_id as pivot_user_id, plugins_user.plugins_id as pivot_plugins_id, plugins_user.contents as pivot_contents from plugins inner join plugins_user on plugins.id = plugins_user.plugins_id where plugins_user.user_id = 1 limit 1)

请帮我解决这个问题。

谢谢

看起来在你的迁移中,你的 table 名字是

`plugin_user` 

但是搜索

的查询
`plugins_user`

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

问题出在您 table 的名字上。该错误说它正在寻找 plugins_user 但您的迁移显示 plugin_user table 缺少秒。这可能是由于模型的命名 Plugins 应该是 Plugin

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