我的目標。 我有3個Laravel機型:用戶,活動和campaign_players。我想獲取關於用戶的信息,以及他/她正在玩的活動。Laravel樞軸表未找到
問題所在。 當我運行此查詢:
$campaigns = user::with(['campaigns_playing'])->where('id', $id)->get();
它給了我這個消息:
「基表或視圖未找到:1146表 'sagohamnen.campaign_players' 不存在(SQL:從
sh_campaigns
內加入 選擇sh_campaigns
。*,campaign_players
。user_id
爲pivot_user_id
,campaign_players
。id
爲上sh_campaigns
。id
=campaign_players
。id
其中campaign_players
。user_id
(2))」
看起來它找不到表名,出於某種原因,難道你們有什麼想法是什麼造成的問題,以及如何解決它?
這裏從我的模特和it's數據庫表短代碼段。
用戶
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']);
});
看起來可能有幾件事錯在這裏。你得到的第一個錯誤是'campaign_players'表不存在。從你發佈的代碼看來,你已經命名了表sh_campaign_players。 – tam5
感謝您的評論。是的,我寫了模型的名字,叫做campaign_players。你的意思是我應該寫MySql表名而不是模型? – Olof84
@Ruffles說如何傳遞表的名字是正確的。另外,我會鼓勵你閱讀Laravel [docs](https://laravel.com/docs/5.2/eloquent-relationships)。有一些鼓勵的慣例。比如在這種情況下調用數據透視表'campaign_user'。 – tam5