modelnamespacesphalconmagic-function

Phalcon: Model relationships with Namespaces


I'm just trying to set up models with namespaces. That part's simple. It's the relationship part that I'm having a tough time with.

I have these two models (these are stripped down):

<?php

namespace My\App\V1\Models;

class Movies extends \My\Namespace\Path\Base
{
}

?>



<?php

namespace My\App\V1\Models

class Genres extends \My\Namespace\Path\Base
{
    public function initialize()
    {
        $this->hasMany('id', 'Movies', 'genre_id');
    }

    public function howManyMovies()
    {
        return $this->countMovies();
    }
}

?>

So... as is, this will give me:

Cannot redeclare class My\App\V1\Models\Movies ....

So, I started thinking it has something to do with namespaces. So... I change the hasMany to:

$this->hasMany('id', 'My\\App\\V1\\Models\\Movies', 'genre_id');

I can put backslashes in front of the "My" or not, but either way I then get:

The method "countMovies" doesn't exist on model "My\App\V1\Models\Genres"

I try changing that line to:

return $this->countMyAppV1ModelsMovies();

... which is rather verbose, but whatever. I still get a "method doesn't exist" error.

What am I missing?


Solution

  • OK. After much time of trying to figure this out, then 5 minutes after posting, I get it....

    One must use an alias:

    $this->hasMany('id', 'My\\App\\V1\\Models\\Movies', 'genre_id', ['alias'=>'Movies']);
    

    I'll leave this here for anyone else who may need it.