Mysql
 sql >> Database >  >> RDS >> Mysql

PDO FETCH_CLASS con tabelle unite

Non c'è supporto per direttamente in PDO per quanto ne so. In genere, se è necessario creare un grafico a oggetti complesso dal risultato di una query, questa è responsabilità di un ORM.

Se hai bisogno di questa funzionalità, ti consiglio di usare Dottrina o Promuovi invece di scrivere qualcosa da soli. Ce ne sono anche altri che potrebbero essere più leggeri, ma non ho esperienza con loro.

MODIFICA:

Penso che forse ho frainteso la domanda come sono sicuro che altri potrebbero. Penso che la vera domanda fosse come ottenere l'accesso alle colonne unite, non necessariamente come creare un oggetto da esse.

In tal caso semplicemente utilizzando un metodo standard di arry fethc come PDO::FETCH_ASSOC , PDO::FETCH_NUMERIC o PDO::FETCH_BOTH ti darà tutte le colonne che hai interrogato.

Quindi se vuoi trasformarlo in un "grafico di oggetti" devi farlo manualmente non usando PDO::FETCH_CLASS .

Ad esempio:

//$db is pdo:
// also notice im aliase the columns prefixing the name so that we can tell what belongs to
// post and what belongs to user, an alternative approach would be to use FETCH_NUMERIC,
// which just uses the column positions from the seelct statement as the keys
// so in this case post.id would be in the array as key 0, and user.name would be in the
// array as key 4
$stmt = $db->prepare('SELECT post.id as p_id, 
       post.text as p_text, 
       post.user_id as p_user_id, 
       user.id as u_id, 
       user.name as u_name
FROM POST INNER JOIN User on post.user_id = user.id');

$stmt->execute();

while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
   print_r($row);
   /* will output:
      Array (
         'p_id' => 'value'
         'p_text' => 'value'
         'p_user_id' => 'value'
         'u_id' => 'value',
         'u_name' => 'value'
      )
   So now you need to decide how to create your objects with the information returned
   */
}