0

我的目标。 我有 3 个 Laravel 模型:usercampaigncampaign_players。我想获取有关用户的信息,以及他/她正在玩的活动。

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

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

它给了我这个信息:

“未找到基表或视图:1146 表 'sagohamnen.campaign_players' 不存在(SQL:选择 . sh_campaigns* campaign_players、. user_idas pivot_user_id、 .as from inner join on . = . where .in ( 2))”campaign_playersidpivot_idsh_campaignscampaign_playerssh_campaignsidcampaign_playersidcampaign_playersuser_id

由于某种原因,它看起来找不到表名。你们知道导致问题的原因以及如何解决吗?

这是我的模型和它的数据库表中的简短代码片段。

用户

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']);
});
4

1 回答 1

1

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

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

于 2016-08-19T13:47:08.580 回答