首页 > 解决方案 > Laravel 5.6 - 雄辩的多对多错误1066

问题描述

在我的 laravel 5.6 项目中,我遇到了多对多关系的问题。我已经有了一些不同的多对多关系,但我找不到这个关系有什么问题。我已经尝试过google和stackoverflow,但找不到答案。

所以,我有 3 张桌子;球员,球队和球员_in_teams 我想展示一个球员和他所属的所有球队。

这是我的(简单)表格布局:

团队 - id - teamName

玩家 - id - firstName - lastName

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

PlayersInTeam.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 不是唯一的表/别名:'players_in_teams'(SQL:选择. players_in_teams* players_in_teams,. FKteamIDas pivot_FKteamID,.as from inner join on . = . where . =1)(查看:.. /resources/views/players/showplayer.blade.php)players_in_teamsFKplayerIDpivot_FKplayerIDplayers_in_teamsplayers_in_teamsplayers_in_teamsidplayers_in_teamsFKplayerIDplayers_in_teamsFKteamID

如果希望有人看到我所缺少的,

提前致谢!

标签: phpmysqllaravel-5laravel-5.6

解决方案


函数的参数设置为数据透视表。您应该将它们设置为最终模型。尝试这个:

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

推荐阅读