Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



66.0k
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:

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

// How to use $sample->speciments; ```