gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:31:32 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com