我的 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_teams
。FKteamID
为 pivot_FKteamID
、players_in_teams
。FKplayerID
为来自 players_in_teams
的 pivot_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/