在我的laravel5.6项目中,我遇到了一个多对多关系的问题。我已经有了一些不同的多对多的关系,但我找不到这其中有什么错。我已经试过google和stackoverflow了,但是找不到答案。
所以,我有三张table;球员,球队和球员在球队中我想展示一个球员和他所属的所有球队。
这是我的(简单)表格布局:
团队-id-团队名称
玩家-id-名字-姓氏
球员积分-id-fkplayerid-fkteamid
我的代码:
播放器.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');
}
}
团队.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');
}
}
播放器集成.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PlayersInTeam extends Model
{
protected $fillable = ['FKteamID', 'FKplayerID'];
}
播放器控制器.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 not unique table/alias:'players\u in\u teams'(sql:select) players_in_teams
.*, players_in_teams
. FKteamID
作为 pivot_FKteamID
, players_in_teams
. FKplayerID
作为 pivot_FKplayerID
从 players_in_teams
内部连接 players_in_teams
在 players_in_teams
. id
= players_in_teams
. FKplayerID
哪里 players_in_teams
. FKteamID
=1)(视图:../resources/views/players/showplayer.blade.php)
如果希望有人看到我错过了什么,
提前谢谢!
2条答案
按热度按时间bjg7j2ky1#
函数的参数设置为透视表。你应该把它们设置成最终的模型。试试这个:
5anewei62#
我会确保在迁移过程中,联接表上的外键设置正确。像这样: