laravel5.6-雄辩的多对多错误1066

o2g1uqev  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(294)

在我的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_FKplayerIDplayers_in_teams 内部连接 players_in_teamsplayers_in_teams . id = players_in_teams . FKplayerID 哪里 players_in_teams . FKteamID =1)(视图:../resources/views/players/showplayer.blade.php)
如果希望有人看到我错过了什么,
提前谢谢!

bjg7j2ky

bjg7j2ky1#

函数的参数设置为透视表。你应该把它们设置成最终的模型。试试这个:

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

5anewei62#

我会确保在迁移过程中,联接表上的外键设置正确。像这样:

$table->foreign('FKplayerID')->references('id')->on('players')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('FKteamID')->references('id')->on('teams')->onDelete('cascade')->onUpdate('cascade');

相关问题