We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Guide me to start with Phalcon queries

Hi!

I'm new to Phalcon and tryin to dive into such a rich functionality fast. So please help me to sove a little problem to get an idea how to work with it next.

I have a "Permissions" model (and table) from Vokuro example (btw renamed it to singular manner as "Permission"). So I want to iterate throw the model data to build the ACL.

My idea is in that I have to get all resources from Permission model, then get all the actions for the current resource. Then I'm adding this resource with fetched actions to ACL.

So the problem constist of understanding of queries. Btw I'm certified DB specialist and there is no difficulty to build a proper query. But for now we're talking about Phalcon models.

What I have:

$resources = Permission::find([
"columns" => "resource",
"distinct" => "resource"
]);

foreach ($resources as $resource) {
    $actions = Permission::find([
        "resource = :resource:",
        "columns"   => "action",
        "distinct"  => "action",
        "bind"      => ["resource" => $resource->resource],
        "hydratation" => \Phalcon\Mvc\Model\Resultset::HYDRATE_ARRAYS
    ]);
}

Next I want to build an array of actions but have no idea how to...

Please say me where I'm wrong and how to easily and properly realise my idea?

P.S. Oh such an ugly shit... Markdown fails any marking...

edited May '15

Hi,

iam not sure what is your problem, but maybe this fit your needs:

$resources = Permission::find(array(
        "columns" => "resource", 
        "distinct" => "resource" 
));

foreach ($resources as $resource) { 
    $actions = Permission::find(array( 
        "resource = :resource:", 
        "columns" => "action", 
        "distinct" => "action", 
        "bind" => array(
                "resource" => $resource->resource
            )
    ));

    // get array of actions
    foreach ($actions as $action) {
        $arrayOfActions = array();
        $arrayOfActions[] = $action->action;
    }

    // do what you need with arrayOfActions

}


2.6k
Accepted
answer
edited May '15

Did it that way:

    $privateResources = $this->db->query("
        SELECT resource, GROUP_CONCAT(DISTINCT action SEPARATOR ',') actions
        FROM permission
        GROUP BY resource");
    $privateResources->setFetchMode(\Phalcon\Db::FETCH_ASSOC);
    $privateResources = $privateResources->fetchAll($privateResources);

    foreach ($privateResources as $resourceItem)
        $acl->addResource(
            new AclResource($resourceItem['resource']),
            explode(",", $resourceItem['actions'])
        );