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

From a PHQL Result to a Model

Hello, is it possible to create again a Model from a QueryBuilder Result with there relations?

My solution so far is to create a new model after the query again with the result like

$model->assign(array('id'=>1,'name'=>2,...);

but how does that work with relations? is there already an easier way to make it kind of automatic? Thanks PAt



4.7k
Accepted
answer

Hmm, i dont realy understand your question, but i think yes. If you use in PHQL(without column select), so in result u can use the model functions and logic. I will give u an example:

    <?php
    // Our model example
    namespace Models;

    class Articles extends \Adapters\Models
    {
        public $id;
        public $title;
        public $date;
        public $content;
        public $summary;
        public $slug;

        public $thumb_sizes = array(
            array(345, 260),
            array(100, 100)
        );

        // etc...
        $phql = "SELECT * FROM Models\Articles";
        $rows = $this->modelsManager->executeQuery($phql);

        foreach($rows as $row) {
            d($row->thumb_sizes); // here u will get model thumb_sizes
        }

Like u see, still after PHQL query u can use model functions, filters and all. This works with two models too- like :

  $phql = "SELECT Cars.*, Brands.* FROM Cars LEFT OUTER JOIN Brands";
  $rows = $manager->executeQuery($phql);

  // ...
  foreach($rows as $row) {
    // $row->Cars->title 
    // $row->Brands->something
  }

Good luck :)

ahh thanks for the answer. the column was the problem that i just got the "row" class and not the real model.

$query->column(array('id','user'));

thanks pat

U welcome :) Yes, column was the problem :) May the force be with u :)

edited Jan '16

I guess you meant something like partial model like in symfony/doctrine, unfortunately there is no such an option in phalcon. You have to select whole table to create model class. If you dont then you got row object.