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

Getting together relation

I have very difficult relations on my tables. I've added a few relations to my models. (https://docs.phalcon.io/en/latest/reference/models.html#bidirectional-relations) but as result from the ::find() I get a complex building of objects and arrays. Here is an example: What I got:
id | headerID | contentID | name
1 | 1 | 1 | test
2 | 1 | 2 | value
3 | 2 | 1 | test

But what I want to get:
id | headerName | headerContent | contentName | name
1 | sample | sample | sample | test
2 | sample2 | sample | sample | value

So I want something like "SELECT ... FROM ... LEFT JOIN ..." But I don't want to write an extra statment for that.

Does someone know a method to do this automatically by code?

The reason why I want it is that I don't want so many foreach-Loops.



51.2k

Can you provide your relations in model ? You could have for example something like this:

// HeaderContentTable id | header_id | content_id | name

// HeaderTable id | name | content

// ContentTable id | name


class HeaderContentTable extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo('content_id', 'ModelNamespace\ContentTable', 'id', array(
            'alias' => 'content',
            'reusable' => true
        )); 

        $this->belongsTo('header_id', 'ModelNamespace\HeaderTable', 'id', array(
            'alias' => 'header',
            'reusable' => true
        ));         
    }
}

Then, using find method you can get this:

$results = HeaderContentTable::find();

foreach($results as $result) {
    echo "ID:", $result->id; // or $result->getId(); if your are using getters and setters
    echo "Header name:", $result->header->name; // or $result->header->getName(); if your are using getters and setters
    echo "Header content: ", $result->header->content;
    echo "Content name: ", $result->content->name;
    echo "Name: ", $result->name; 
}