【问题标题】:Get a record with its realtionship as an array以数组形式获取记录
【发布时间】:2017-02-26 13:58:17
【问题描述】:

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

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"
            }
        ]
    }
}

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

【问题讨论】:

    标签: phalcon phalcon-orm


    【解决方案1】:

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

    如果您真的只想要 1 个预算及其所有budget_items,您可以使用您在上面定义的关系。

    $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
    

    【讨论】:

    • 在那种情况下会有两个请求。一份用于预算,一份用于其项目。那么,没有办法使用 phql 或查询生成器来获取记录及其关系作为单个数组吗?
    • 您无法仅通过查询来实现此目的。如果您想使用 QueryBuilder 方式,我将创建一个辅助函数,它迭代结果并按照您要求的方式转换它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2015-02-13
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多