我可以用redbeanphp做多映射吗?

时间:2015-03-17 07:41:10

标签: redbean

我可以加载一个对象,它只与一个查询有关系吗?

所以,如果我有

select * from parent inner join child on parent.id = child.parent_id

我可以通过该查询通知selfChild的父bean数组吗?

像papper中的多映射一样: https://github.com/StackExchange/dapper-dot-net#multi-mapping

2 个答案:

答案 0 :(得分:1)

是的,你可以。这在RedBean手册中记录为“Find Multiple”。

查询示例:

<?php

require 'rb.php'; // 4.2.4, for the record

R::setup();

// --- Fixtures ---

$parent = R::dispense('parent');
$parent->name = "Foo";

$child = R::dispense('child');
$child->name = "Bar";
$childId = R::store($child);

$parent->ownChildList[] = $child;
$parentId = R::store($parent);

// --- Multi Mapping ---

$beans = R::findMulti( 'parent,child', '
    SELECT parent.*, child.* FROM parent
    INNER JOIN child ON parent.id = child.parent_id
    WHERE parent.id = ?
', [$parentId], [
    [
        'a' => 'parent',
        'b' => 'child',
        'matcher' => function($parent, $c) {
            return $parent->id == $c->parent_id;
        },
        'do' => function($p, $c) {
            $p->noLoad()->ownChildList[$c->id] = $c;
        }
    ]
]);

// Ensure we don't get lazily loaded results...
R::nuke();

echo $beans['parent'][$parentId]->ownChildList[$childId]->name, "\n";

输出:

Bar

我们赢了。

答案 1 :(得分:0)

$parent = R::dispense('parent');
$parent->name = "darth";

$child = R::dispense('child');
$child->name = "Luke";

$parent->ownChildList[] = $child;
$parent_id = R::store($parent);

// now fetch
$parent = R::load('parent' $parent_id);

echo "$parent has the following kids:";
foreach ($parent->ownChildList as $child){
    echo $child->name . ", ";
}