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

magic getter

I'm trying to get use the magic getter.

I get this: Phalcon\Mvc\Model\Exception: The method "getGroups" doesn't exist on model "Module\Inventory\Models\Items"

Can someone please let me know what I'm doing wrong?

Table: Items {ItemID, ItemGroupID, Name}, ItemGroups {ItemGroupID, GroupName}

// Model: Items

namespace Module\Inventory\Models;

class Items extends BaseModel
{
    function initialize()
    {
        $this->setSource("xyz_items");

        $this->belongsTo('ItemGroupID', '\Module\Inventory\Models\Groups', 'ItemGroupID', array(
            'reusable' => true
        ));
    }
}
// Model: Groups

namespace Module\Inventory\Models;

class Groups extends BaseModel
{
    public $ItemGroupID;
    public $Name;

    function initialize()
    {
        $this->setSource("xyz_groups");

        $this->hasMany('ItemGroupID', '\Module\Inventory\Models\Items', 'ItemGroupID');
    }
}
// Controller: Items

use Module\Inventory\Models\Items as Items;

class IndexController extends ControllerBase
{

    public function indexAction()
    {
        $items = Items::find();

        $this->view->setVar("items", $items);
    }

}
// View: Index

foreach ($items as $item) 
{
    echo $item->getGroups()->GroupName ?>
} 


98.9k
Accepted
answer

Alias the relation:

$this->belongsTo('ItemGroupID', '\Module\Inventory\Models\Groups', 'ItemGroupID', array(
    'reusable' => true
    'alias' => 'groups'
));