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

因此,我有3张桌子;球员,球队和球员
我想向球员和他所参与的所有团队展示。

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

队伍
- ID
- 队名

玩家们
- ID
- 名字
- 姓

玩家团队
- 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不是唯一的表/别名:'players_in_teams'(SQL:选择players_in_teams。*,players_in_teamsFKteamID作为pivot_FKteamIDplayers_in_teamsFKplayerID来自pivot_FKplayerID上的players_in_teams内部联接players_in_teams中的players_in_teamsid = players_in_teamsFKplayerID其中players_in_teamsFKteamID = 1)(视图:../resources/views/玩家/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/

10-11 03:38