简体   繁体   English

有没有一种方法可以通过PHP MySQL PDO中的表名对数组进行索引

[英]is there a way to get array indexed by table names in PHP MySQL PDO

I'm using php with MySQL PDO, so my goal is to do a select from multiple tables at the same time, the problem is those tables contains some identical field names (like status, user_id, deleted etc). 我在MySQL PDO中使用php,所以我的目标是同时从多个表中进行选择,问题是这些表包含一些相同的字段名称(例如status,user_id,deleted等)。

So, is there a way to get the result in an array indexed by table names like in cakePHP: 因此,有没有一种方法可以将结果获取到由表名称索引的数组中,例如cakePHP:

//--SQL Query
$db->query('Select users.id, users.name, users.status, users.deleted, 
books.id, books.name, books.status, books.deleted where 
users.id=books.user_id AND user.id=1');

//--result I need
array (
  ['users']=>array(
    'id'=>1,
    ['name']=>'test',
    ['status']=>'active',
    ['deleted']=>0
  ),
  ['books']=>array(
    ['id']=>2,
    ['user_id']=>1,
    ['name']=>'Lost Word',
    ['status']=>'pending',
    ['deleted']=>0
  )
)

PDO doesn't have any feature to do this for you. PDO没有任何功能可以为您执行此操作。 You have to write code to process the rows returned by PDO. 您必须编写代码来处理PDO返回的行。

But you'll have to know which column came from which table yourself. 但是,您必须自己知道哪个列来自哪个表。 Even PDOStatement::getColumnMeta() doesn't return the origin table for each column, because sometimes an expression in the select-list doesn't correspond to any single table. 甚至PDOStatement :: getColumnMeta()也不返回每一列的原始表,因为有时选择列表中的表达式并不对应于任何单个表。

For example, how would you arrange the result for this query? 例如,您将如何安排此查询的结果?

SELECT users.deleted + books.deleted AS `either_deleted`
FROM users JOIN books ON users.id=books.user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM