php - Laravel 5.6 - Eloquent 多对多错误 1066

标签 php mysql laravel-5 laravel-5.6

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

所以,我有 3 张 table ;球员、球队和player_in_teams 我想向一名球员以及他所属的所有球队展示。

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

团队 - ID - 团队名称

玩家 - ID - 名 - 姓氏

团队中的玩家 - ID - FK玩家ID - FK团队ID

我的代码:

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

团队.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 不唯一的表/别名:'players_in_teams'(SQL:选择players_in_teams.*,players_in_teamsFKteamIDpivot_FKteamIDplayers_in_teamsFKplayerID 为来自 players_in_teamspivot_FKplayerID > 在 players_in_teams.id = players_in_teams.FKplayerID 上内部加入 players_in_teams,其中 players_in_teams.FKteamID = 1)(查看:../resources/views/players/showplayer.blade.php)

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

提前致谢!

最佳答案

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

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

关于php - Laravel 5.6 - Eloquent 多对多错误 1066,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50590998/

相关文章:

php - 页面在本地主机上运行良好但无法在托管服务器上运行

mysql - 在sql中存储300位数字

Laravel 5 Dotenv 用于特定子域

php - Doctrine Repository getEntityManager() 确实返回空

php - SQL/PHP : Joins with no matches on the other table (multiple tables)

mysql - 自增Id和key问题(MySQL)

mysql - 在具有相同查询的 MySQl 中使用 And & OR 条件

php - Laravel - 无法将经过身份验证的用户的 ID 放入数组中

php - Laravel 邮件奇怪的超时错误

php - APN php 代码给出警告 : stream_socket_client() [function. stream-socket-client] : unable to connect to ssl://gateway. sandbox.push.apple.com:2195