从多个MySQL表高效地检索PHP对象
我有以下PHP类: User.php forummessage 获取具有给定所有属性的Chatmessage数组的最快、最高效的方法是什么 现在,我有一个使用此方法的PDO包装器类:从多个MySQL表高效地检索PHP对象,php,mysql,class,pdo,Php,Mysql,Class,Pdo,我有以下PHP类: User.php forummessage 获取具有给定所有属性的Chatmessage数组的最快、最高效的方法是什么 现在,我有一个使用此方法的PDO包装器类: /** * Performs a query to the database and returns the desired type * @param string $statement the pdo query * @param array $params the params * @param st
/**
* Performs a query to the database and returns the desired type
* @param string $statement the pdo query
* @param array $params the params
* @param string $returntype optional param (default: 'bool'), should be either 'bool', 'array' or a valid class name
* @return bool|array returns either a bool depending on the success of the query or an array with the resulting data
*/
function query($statement, $params = array(), $returntype = 'bool');
如果我将一个有效的类名作为$returntype传递,那么这个方法使用$stmt->fetchAll\PDO::FETCH_class,$returntype;以返回类实例数组
我会这样做:
// Automatically generates an array of Forummessage
$arrayOfForummessage = $wrapper->query('
SELECT
forummessage.id AS id, // NOTE: I MAKE SURE THE PROPERTIES MATCH TO THE PHP CLASS
user_id AS user_id,
message
datetime,
name AS user_name // NOTE: NOT USED YET
FROM user, forummessage
WHERE user.id = forummessage.user_id
', array(), 'Forummessage');
这可以很好地工作,但正如您所理解的,属性user仍然为NULL。如何确保用户属性已给定?如您所见,数据在查询中
当然,我可以在Forummessage构造函数中创建一个for循环并查找正确的属性,以便填充并创建一个User实例并将其分配给Forummessage类属性。问题是,当有许多属性和许多对象时,这是非常缓慢的。如果您有建议,我很想了解更多信息。查看如何使用-这将帮助您解决问题。您必须放弃PDO::FETCH_类,而改为手动操作。根据需求,有N种方法可以做到这一点,但一种简单的方法是:根据某种约定命名相关列,例如使用此处的user_uu前缀。然后您的代码可以在u上拆分,收集所有用户列,检查new Forummessage是否有一个属性$user,该属性是一个用户实例,并执行正确的操作。这不是MySQL的问题,而是PHP的问题,我已经加入了表格。Jon,我考虑过将值传递给构造函数,但是当我手动循环时,速度不是很慢吗?
id name
------------
1 tester
2 anyuser
...
id user_id message datetime
---------------------------------------------
1 1 hello... 2014-04-04 12:00:00
2 2 yoyo... 2014-04-04 12:00:10
...
/**
* Performs a query to the database and returns the desired type
* @param string $statement the pdo query
* @param array $params the params
* @param string $returntype optional param (default: 'bool'), should be either 'bool', 'array' or a valid class name
* @return bool|array returns either a bool depending on the success of the query or an array with the resulting data
*/
function query($statement, $params = array(), $returntype = 'bool');
// Automatically generates an array of Forummessage
$arrayOfForummessage = $wrapper->query('
SELECT
forummessage.id AS id, // NOTE: I MAKE SURE THE PROPERTIES MATCH TO THE PHP CLASS
user_id AS user_id,
message
datetime,
name AS user_name // NOTE: NOT USED YET
FROM user, forummessage
WHERE user.id = forummessage.user_id
', array(), 'Forummessage');