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

Models in controllers

I have a controller that starts off

namespace Controllers;

use \Models\Organisation as Organisation;

class OvniOrg extends \Phalcon\Mvc\Controller {

    //just says hello and lets you know you are in the right place.
    public function hello(){

    echo "Hello!";  

    }

    ///get a list of all organizations
    public function listOrganizations() {

    $phql = "SELECT * FROM Organisation";
    $organisation = $this->modelsManager->executeQuery($phql);

    $data = array();
    foreach ($organisation as $org) {
        $data[] = array(
            'Organisation ID'  => $org->id, 
            'Organisation Name'  => $org->orgName,
            'orgCurrAccessToken'  => $org->orgCurrAccessToken
        );
    }

    if (empty($data)) {
   $data[] = array(
            'status' => "OK",
            'result' => "No data returned from the server for organisations.",
            );
}

    echo json_encode($data, JSON_PRETTY_PRINT);
    }

The controller cannot seem to find the model as I am getting an error that the model cannot be found. I am using Autoload to get the models dir in the bootstrap file.

Model "Organisation" could not be loaded.

I am fairly new to MVC so I am not sure if this is even the correct way to process data. I admit ignorance,

Thanks

T

I believe your application is using a single module

    use \<namespace>\Models\Organisation as Organisation;

Remember to use the namespacing well. https://docs.phalcon.io/en/latest/reference/namespaces.html



6.5k
Accepted
answer

This worked. I needed to add use to the top of the page and then point to the model. Not sure if you can use PHQL but this works much better. Hope this helps another noob!

namespace Controllers;
use \Models\Organisation;

class ExampleController extends \Phalcon\Mvc\Controller {

    public function pingAction() {

        echo "pong";
    }

    public function testAction($id) {
        echo "test (id: $id)";
    }

    public function skipAction($name) {
        echo "auth skipped ($name)";
    }

    public function getOrgAction(){

        $organisation = Organisation::findFirst();

    $data = array();
    foreach ($organisation as $org) {
        $data[] = array(
            'Organisation ID'  => $org->id, 
            'Organisation Name'  => $org->orgName,
            'orgCurrAccessToken'  => $org->orgCurrAccessToken
        );
    }

    if (empty($data)) {
   $data[] = array(
            'status' => "OK",
            'result' => "No data returned from the server for organisations.",
            );
}

    echo json_encode($data, JSON_PRETTY_PRINT);

    }
}