mcv mcv - 1 year ago 57
PHP Question

PHP PDO when fetching data, can data be fetched into an Object which contains another Object?

Out of pure curiosity, can anyone quickly tell me if it is possible? I didn't implement it that way, but looking back, I wonder if it could be done. Here is the scenario:

A table of products, services and a relational table between the both defining costs

Product ID | Name
1 | Product A
2 | Product B

Service ID | Name
1 | Service A
2 | Service B
3 | Service C

Price ID | Cost | Product ID | Service ID
1 | 1 | 1 | 1
2 | 2 | 1 | 3
3 | 3 | 2 | 2
4 | 4 | 2 | 3

So if there were Table Data Objects, there would be:

  • Class Product with attributes: id, name, array of Services.

  • Class Service has attributes: id, name, cost

//$query = obtain a list of all products with services and prices;
//$query = obtain a product and all it's associated services and prices;
$statement = $pdo->prepare($query);
$statement -> execute();
$results = $statement ->fetchAll(PDO::FETCH_CLASS,"Product");

Answer Source

PDO does not seem to have support for nesting any relational data into a given object. Have a look at the documentation of fetch. You could probably build the logic required to load the relations of a product into the Product class itself and invoke it manually.

As PDO injects the values of the class properties prior to __construct() you might be able to pull off some voodoo magic within the constructor, I'm not too sure of that though.

Either way, this is typically one of those things a solid ORM layer can provide you with. And some are out there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download