在PDO中加载引用的表

时间:2012-01-08 11:04:06

标签: php sql pdo

我有一些看起来像这样的对象:

class A {
     #From database
     public $id;
     public $name;
     public $desc;
     public $bId; 
     public $cId;

     #In php
     public $b; #Points to a B instance
     public $c; #Points to a c instance
}

class B {
     public $id;
     public $name;
     public $desc;
}

class C {
     public $id;
     public $name;
     public $desc;
}

我想从表中加载A对象,同时加载B和C对象。我可以做到这一点的一种方式是:

$a = $db->query("SELECT * FROM table_a WHERE id = $id")->fetchObject(A);
$a->b = $db->query("SELECT * FROM table_b WHERE id = {$a->bId}")->fetchObject(B);
$a->c = $db->query("SELECT * FROM table_c WHERE id = {$a->cId}")->fetchObject(C);

但是,这需要三个查询。如果我想获得一组A对象,则每个项目需要两个查询。我可以通过以下方式获取一个查询中的所有数据:

$data = $db->query("
    SELECT
        table_a.name   as `name`,
        table_a.desc   as `desc`,
        table_b.name   as `b.name`,
        table_b.desc   as `b.desc`,
        table_c.name   as `c.name`,
        table_c.desc   as `c.desc`,
    FROM table_a
        LEFT JOIN table_b on table_b.id = table_a.bId
        LEFT JOIN table_c on table_c.id = table_a.cId
    WHERE table_a.id = $id
")->fetch();

$a = new A();
$a->name = $data['name'];
$a->desc = $data['desc'];
$a->b = new B();
$a->b->name = $data['b.name'];
$a->b->desc = $data['b.desc'];
$a->c = new B();
$a->c->name = $data['c.name'];
$a->c->desc = $data['c.desc'];

这只给我一个关联数组,这意味着我需要手动构建我的对象。此外,它要求我在查询中列出所有可能的属性。

有更好的方法吗?或者在这里做3个查询是完全可以的吗?

0 个答案:

没有答案