我的laravel 5.6项目中存在多对多关系的问题。我已经有了一些不同的多对多关系,但我无法找到这个问题。我已经尝试过google和stackoverflow,但无法找到答案。
所以,我有3张桌子;球员,球队和球员_in_teams 我想展示一名球员和他所参加的所有球队。
这是我的(简单)表格布局:
小组 - ID - teamName
球员 - ID - 名字 - lastName
PlayersInTeams - ID - FKplayerID - FKteamID
我的代码:
Player.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
protected $fillable = [
'firstName', 'lastName'
];
public function teams() {
return $this->belongsToMany('App\PlayersInTeam', 'players_in_teams', 'FKteamID', 'FKplayerID');
}
}
Team.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $fillable = ['FKuserID', 'teamName', 'teamDescription', 'FKmediaID'];
public function players(){
return $this->belongsToMany('App\PlayersInTeam', 'players_in_teams', 'FKteamID', 'FKplayerID');
}
}
PlayersInTeam.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PlayersInTeam extends Model
{
protected $fillable = ['FKteamID', 'FKplayerID'];
}
PlayerController.php
public function index()
{
$players = Player::all();
return view('players.index', compact('players', $players));
}
showplayer.blade.php
<li>{{ $player->firstName.' '.$player->lastName }}</li>
<li>{{ $player->id }}</li>
@if($player->teams)
<li>{{ $player->teams->id }}</li>
@endif
我收到的完整错误:
SQLSTATE [42000]:语法错误或访问冲突:1066不唯一的表/别名:&#39; players_in_teams&#39; (SQL:选择players_in_teams
。*,players_in_teams
。FKteamID
为pivot_FKteamID
,players_in_teams
。FKplayerID
为pivot_FKplayerID
来自{{ 1}}内部联接players_in_teams
位于players_in_teams
。players_in_teams
= id
。players_in_teams
其中FKplayerID
。players_in_teams
= 1)(查看:../ resources / views / players / showplayer.blade.php)
如果希望有人看到我失踪的东西,
提前致谢!
答案 0 :(得分:0)
功能的参数设置为数据透视表。您应该将它们设置为最终模型。试试这个:
public function teams() {
return $this->belongsToMany('App\Team', 'players_in_teams', 'FKplayerID', 'FKteamID');
}
public function players(){
return $this->belongsToMany('App\Player', 'players_in_teams', 'FKteamID', 'FKplayerID');
}
答案 1 :(得分:0)
我会确保您的迁移中加入表上的外键已正确设置。像这样:
$table->foreign('FKplayerID')->references('id')->on('players')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('FKteamID')->references('id')->on('teams')->onDelete('cascade')->onUpdate('cascade');