We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Help with model relations (Namespaced)

Hey, big fan here, also in a big hurry, hope someone can find the time to give me some advice. I have two models but I can't get them to work with the magic getters, here there are:

Samples.php Specimens.php

Each sample has several specimens, and I want to get them like this (In a Controller):

$sample->specimens;

Or:

$sample->getSpecimens();

I've tried hundreds of things and nothing seems to work, I'm doing individual queries for each sample, but as you might guess, this is not practical.

First post on the forum. I'm a suporter on patreon, I really, really like the concept behind the framework, and I believe that we can make Phalcon the best PHP framework of all.



93.7k
Accepted
answer

Here is a bigger example of relation, notice the alias parameter:

class Samples extends \Phalcon\Mvc\Model
{
    public function initialize(){
        $this->hasMany(
            "id",
            "Qc\\Models\\Specimens",
            "sample_id", [
                'alias' => 'specimens', // THIS IS THE IMPORTANT THINGIE
                'reusable' => true,
                'params' => [
                    'order' => 'id ASC',
                    'conditions' => 'is_active = :is_active:',
                    'bind' => [
                        'is_active' => 1
                    ]
                ]
            ]
        );
    }
}

// How to use
$sample->speciments; 

Holy smokes that was fast! And you shure know what you're doing! Awsome! Thanks!

Here is a bigger example of relation, notice the alias parameter:

class Samples extends \Phalcon\Mvc\Model
{
   public function initialize(){
       $this->hasMany(
           "id",
           "Qc\\Models\\Specimens",
           "sample_id", [
               'alias' => 'specimens', // THIS IS THE IMPORTANT THINGIE
               'reusable' => true,
               'params' => [
                   'order' => 'id ASC',
                   'conditions' => 'is_active = :is_active:',
                   'bind' => [
                       'is_active' => 1
                   ]
               ]
           ]
       );
   }
}

// How to use
$sample->speciments;