【问题标题】:access violation Joining a table on another table twice using Laravel访问冲突使用 Laravel 在另一个表上加入一个表两次
【发布时间】:2014-03-17 22:21:28
【问题描述】:

所以我得到了一个名为 matches 的表,其中包含 2 个团队 ID,这些团队位于同一个名为 clans 的表中

匹配

team1_id | team2_id

 2     |    4

 1     |    2

 4     |    1

部落

ID | Name 

 2 | abc 

 1 | cde

 4 | efg

我的目标是,当我在网页上打印出来时,它会显示团队名称而不是他们的 ID。现在简单解释一下,我用的是laravel,代码如下:

    $unfinished = DB::table('matches')->where('team1_score', NULL)
        ->join('matches', 'matches.team1_id', '=', 'clans.id')
        ->join('matches', 'matches.team2_id', '=', 'clans.id')
        ->select('clans.clan_name as team1_name', 'clan_name as team2_name', 'matches.id'
        )->get();

我需要将它们全部存储在 $unfinished 中。自然,这段代码不起作用,我想我明白为什么。然而,我只是想不通,如何解决这个问题才能让它发挥作用。它吐出以下exakt错误:

SQLSTATE[42000]: 语法错误或访问冲突: 1066 Not unique table/alias: 'matches' (SQL: select clans.clan_name as team1_name, clan_name as team2_name, @987654329 @.id, tournaments.name from matches 内连接 tournaments on tournaments.id = matches.matches.tournaments_id 内连接 @9876544339@@9876544339@@978 @ = clans.id 内部连接 ​​matches matches.team2_id = clans.id 其中team1_score 为空)

【问题讨论】:

  • SELECT 正在引用来自 clans 的列,但没有命名或别名为 clans 的行源。如果您需要多次引用同一个表,请为该表分配一个别名,并使用别名限定列引用。 DB::table('matches AS m')->where('m.team1_score',NULL)->join('matches AS m1','m1.team1_id', ...

标签: php mysql laravel


【解决方案1】:

使用别名:

$unfinished = DB::table('matches')->where('team1_score', NULL)
    ->join('clans AS clans1', 'matches.team1_id', '=', 'clans1.id')
    ->join('clans AS clans2', 'matches.team2_id', '=', 'clans2.id')
    ->select('clans1.clan_name as team1_name', 'clans2.clan_name as team2_name', 'matches.id'
)->get();

【讨论】:

  • 非常感谢您的帮助!非常赞赏。完美运行!
猜你喜欢
  • 2018-02-11
  • 1970-01-01
  • 2015-09-15
  • 2019-04-22
  • 1970-01-01
  • 2012-05-29
  • 2018-10-04
  • 1970-01-01
  • 2019-01-20
相关资源
最近更新 更多