1

规格:PHP 5 和基于 Codeigniter 框架构建的 mySQL。

我有一个名为的数据库表game,然后是特定的表,例如soccerGamefootballGame。这些运动特定的表格有一个gameId链接回表格的字段game。我有相应的类gamesoccerGame/ footballGame,它们都扩展了game.

当我查找要显示给用户的游戏信息时,我无法弄清楚如何动态链接这两个表。我很好奇是否可以通过一次查询获得所有信息。问题是,我需要先查询game表才能找出运动名称。

如果那不可能,我的下一个想法是用两个查询来完成。让我game_model查询比赛表,然后根据运动名称,调用适当的运动特定模型(即soccer_game_model)并获取运动特定信息。

我还将game对象传递到 中soccer_model,然后soccer_model使用该对象为我构建一个soccerGame对象。这对我来说似乎有点傻,因为我正在构建父对象,然后将其提供给扩展类以创建一个全新的对象?

想法?

谢谢您的帮助。

编辑:

游戏桌

gameId
sport (soccer, basketball, football, etc)
date
other data

足球游戏桌

soccerGameId
gameId
soccer specific information

足球游戏桌

footballGameId
gameId
football specific information

等等其他运动

所以我需要知道这项运动是什么,然后才能决定我需要从哪个运动特定表中提取信息。

更新:

感谢大家的投入。似乎动态 SQL 只能通过存储过程实现,我现在不太熟悉。即使有他们,它仍然有点混乱。现在我将走两条查询路线,一条获取运动名称,然后切换获取正确的型号。

game从现在的 PHP 方面来看,获取一个对象,将其传递给 my soccer_game_model,然后让它返回我一个soccer_game对象,它是原始的子对象,这似乎有点愚蠢game。必须这样做吗?或者我在这里从面向对象的角度错过了什么?

4

3 回答 3

1

To extend on Devin Young's answer, you would achieve this using Codeigniter's active record class like so:

public function get_game_by_id($game_id, $table)
{
    return $this->db->join('game', 'game.id = ' . $table .  '.gameId', 'left')
    ->where($table . '.gameId', $game_id)
    ->get('game')
    ->result();
}

So you're joining the table by the gameId which is shared, then using a where clause to find the correct one. Finally you use result() to return an array of objects.

EDIT: I've added a second table paramater to allow you to pass in the name of the table you can join either soccerGame, footballGame table etc.

If you don't know which sport to choose at this point in the program then you may want to take a step back and look at how you can add that so you do know. I would be reluctant to add multiple joins to all sport tables as you''ll run into issues down the line.

于 2013-03-13T18:24:15.947 回答
1

查看此 Stack Overflow 答案,了解如何通过标准查询进行操作。然后,您可以根据需要将其转换为活动记录(尽管如果您的应用程序中不需要与 DB 无关的调用,这可能会很复杂并且不值得您花时间)。

值得一提的是,执行多个查询并没有错,只是可能比替代方法慢。尝试几个选项,看看最适合您和您的应用程序的选项。

于 2013-03-13T18:29:47.703 回答
1

更新

在查找游戏数据时考虑传递“sport”参数。作为一个隐藏的领域,很可能。然后,您可以在模型中使用 switch 语句:

switch($gameValue) {
  case 'football': $gameTable = "footballGame"; break;
  case 'soccer': $gameTable = "soccerGame"; break;
}

然后将您的查询基于此:

"SELECT * 
FROM ". $gameTable . "
...etc

您可以将表与联接结合起来。http://www.w3schools.com/sql/sql_join.asp

例如,如果您需要从gamefootballGame基于 15 的 footballGameId 获取所有数据:

SELECT *
FROM footballGame a
LEFT OUTER JOIN game b ON a.id = b.gameId
WHERE footballGameId = 15
于 2013-03-13T18:08:02.387 回答