未找到Laravel Pivot表

时间:2016-08-19 13:24:41

标签: laravel eloquent foreign-keys tablename

我的目标。 我有3个Laravel模型:用户广告系列 campaign_players 。我想获得有关用户的信息,以及他/她正在播放的广告系列。

问题。 当我运行此查询时:

$campaigns = user::with(['campaigns_playing'])->where('id', $id)->get();

它给了我这条消息:

  

“未找到基表或视图:1146表   'sagohamnen.campaign_players'不存在(SQL:select   sh_campaigns。*,campaign_playersuser_idpivot_user_id,   来自campaign_players内部联接的idpivot_idsh_campaigns   campaign_players上的sh_campaignsid = campaign_playersid   其中campaign_playersuser_id位于(2))“

由于某种原因,它看起来无法找到表名。你们有什么想法导致问题以及如何解决问题吗?

以下是我的模型和数据库表的简短代码。

用户

protected $table = 'sh_users';
public function campaigns_playing()
{
        return $this->belongsToMany('Sagohamnen\campaign\campaign', 'Sagohamnen\campaign\campaign_players', 'user_id', 'id');
 }

Schema::create('sh_users', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name', 255);
});

广告系列

protected $table = 'sh_campaigns';

Schema::create('sh_campaigns', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name', 255);               
        $table->timestamps();
});

Campaign_players

protected $table = 'sh_campaign_players';

Schema::create('sh_campaign_players', function (Blueprint $table) {
        $table->integer('user_id')->unsigned();
        $table->integer('campaign_id')->unsigned();
        $table->date('date');
        $table->primary(['user_id', 'campaign_id']);
});

1 个答案:

答案 0 :(得分:1)

将数据透视表名称作为第二个参数传递给belongsToMany()方法。它要求输入字符串,而不是模型类路径。

Sagohamnen\campaign\campaign_players更改为sh_campaign_players(或数据库中数据透视表的名称)