Search code examples
phpphalcon

phalconphp hasMany() and belongsTo() not joining


I've been trying to retrieve my data by doing a findFirst() call, but it doesn't work. I've been trying so much and seeking everywhere, but didn't find solution.

I have these tables:

- fruit
    fruit_id
    fruit_name
- fruit_color
    fruit_id
    fruit_color_name

In my fruit model @Initialize(), I declare:

$this->hasOne('fruit_id', 'fruitColor', 'fruit_id');

In my fruit_color model, @initalize(), I have:

$this->belongsTo('fruit_id', 'fruit', 'fruit_id');

When I call find() or findFirst() methods, I can't retrieve anything. when I print out and the debug, I see that no join has been called and I only get a simple SELECT (*).

Do you have any clue?


Solution

  • I think you did not understand the idea of model relations. I will try to explain with examples.

    Model relations do not make Joins at all. They will make additional query when you request the related model.

    Model Relations

    public function initialize()
    {
        $this->hasMany('id', 'Models\ServicesVideos', 'service_id', [
            'alias' => 'videos',
            'params' => [
                'order' => 'position ASC',
                'conditions' => 'type = :type:',
                'bind' => [
                    'type' => get_class($this)
                ]
            ]
        ]);
    }
    

    With the relation defined above you can use it like so:

    $user = Users::findFirst(12);
    $user->videos; // This will return all videos for this user
    

    More info about Model Relations: https://docs.phalconphp.com/en/3.2/db-models-relationships


    However if you need to join two or more tables you want to use the Query Builder.

    $lang = $this->getDI()->getSession()->language;
    $cacheFile = 'news-'. $lang;
    $items = $this->modelsManager->createBuilder()
        ->columns([
            'main.id',
            'main.title',
            'main.slug',
            'main.summary',
    
            'upload.id AS imageId',
            'upload.filename AS imageFilename',
            'upload.ver AS uploadVersion',
        ])
        ->from(['main' => 'Models\News'])
        ->leftJoin('Models\Uploads', 'upload.foreign_key = main.id AND upload.section = "newsImage" AND upload.is_active = "1" AND upload.is_default = "1"', 'upload')
        ->where('main.is_active = 1')
        ->andWhere('main.lang = :lang:', ['lang' => $lang])
        ->orderBy('main.ord ASC')
        ->getQuery()->cache(['key' => $cacheFile])->execute();
    

    More info about the Query Builder: https://docs.phalconphp.com/en/3.2/db-models