0

我有一个具有一对多关系的模型类。

class Budget extends Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->setSource('budgets');

        $this->hasMany('id', BudgetItem::class, 'budget_id');
    }
}

class BudgetItem extends Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->setSource('budget_items');

        $this->belongsTo('budget_id', Budget::class, 'id');
    }
}

因此,一个预算记录有多个budget_items。我想通过所有相关项目的 id 获取预算,所以我构建了一个查询:

$query = $modelsManager->createBuilder()
    ->addFrom(Budget::class, 'b')
    ->leftJoin(BudgetItem::class, 'b.id = bi.budget_id', 'bi')
    ->columns('b.*, bi.*')
    ->where('b.id = :id:', ['id' => 1])
    ->getQuery();

$result = $query->execute();

但结果对我来说看起来很奇怪。

{
    b: {
        id: "1"
    },
    bi: {
        id: "9",
        budget_id: "1",
        amount: "23500"
    }
},
{
    b: {
        id: "1"
    },
    bi: {
        id: "10",
        budget_id: "1",
        amount: "116500"
    }
}

而我期待一个看起来像这样的结果集:

{
    b: {
        id: "1"
        bi: [
            {
                id: "9",
                budget_id: "1",
                amount: "23500"
            }, {
                id: "10",
                budget_id: "1",
                amount: "116500"
            }
        ]
    }
}

有没有办法只获得一个包含两个项目的数组的预算对象?

4

1 回答 1

0

在您的示例中,您没有使用模型关系,而是使用普通左连接的查询构建器。这将始终返回多行。

如果您真的只想要 1 个预算和他的所有预算项目,您可以使用您在上面定义的关系。

$budget = Budget::findFirst(22);
$budget->id; // id of your Budget table and other columns
$budget->budget_items; // This will contain array of all your budget_items relation
于 2017-02-27T05:47:10.623 回答