2016-08-19 122 views
0

我的目標。 我有3個Laravel機型:用戶,活動campaign_players。我想獲取關於用戶的信息,以及他/她正在玩的活動。Laravel樞軸表未找到

問題所在。 當我運行此查詢:

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

它給了我這個消息:

「基表或視圖未找到:1146表 'sagohamnen.campaign_players' 不存在(SQL:從sh_campaigns內加入 選擇 sh_campaigns。*,campaign_playersuser_idpivot_user_idcampaign_playersid爲上sh_campaignsid = campaign_playersid 其中campaign_playersuser_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']); 
}); 
+0

看起來可能有幾件事錯在這裏。你得到的第一個錯誤是'campaign_players'表不存在。從你發佈的代碼看來,你已經命名了表sh_campaign_players。 – tam5

+0

感謝您的評論。是的,我寫了模型的名字,叫做campaign_players。你的意思是我應該寫MySql表名而不是模型? – Olof84

+0

@Ruffles說如何傳遞表的名字是正確的。另外,我會鼓勵你閱讀Laravel [docs](https://laravel.com/docs/5.2/eloquent-relationships)。有一些鼓勵的慣例。比如在這種情況下調用數據透視表'campaign_user'。 – tam5

回答

1

傳遞樞軸表的名稱作爲第二個參數belongsToMany()方法。它要求一個字符串,而不是一個模型類路徑。

變化Sagohamnen\campaign\campaign_playerssh_campaign_players(或任何你透視表的名稱是在數據庫中)