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

custom columns and result set problem

Hello All!

I want try to get the distinct results of a model query so I use the following code:

            $passengers = $this->modelsManager->createBuilder()
                ->columns('title, first_name, last_name')
                ->from('App\Models\Passengers')
                ->Where('first_name like :search: or last_name like :search:', ['search' => $search])
                ->limit(10)
                ->distinct(true)
                ->getQuery()
                ->execute();

But the result returned as "Phalcon\Mvc\Model\Row", so my "Passengers" modal getter not work.

foreach($passengers as $passenger)
{
    echo $passenger->getTitle('formatted'); // Uncaught Error occured
}

Uncaught Error: Call to undefined method Phalcon\Mvc\Model\Row::getTitle()

Is there any solution exists to solve the issue?


My current workaround is as the follow:

            $passengers_query = $this->modelsManager->createBuilder()
                ->columns('title, first_name, last_name=')
                ->from('App\Models\Passengers')
                ->Where('first_name like :search: or last_name like :search:', ['search' => $search])
                ->limit(10)
                ->distinct(true)
                ->getQuery()
                ->getSql();

            // Base model
            $passenger_model = new ReservesPassengers();

            // Execute the query
            $passengers = new Resultset(
                null,
                $passenger_model,
                $passenger_model->getReadConnection()->query($passengers_query['sql'], $passengers_query['bind'], $passengers_query['bindTypes'])
            );

foreach($passengers as $passenger)
{
    echo $passenger->getTitle('formatted'); // Works!
}

Best regards.

This is not an issue, if you explicitly select columns, then the ORM wil discard model info and return a simple row.

If you want your resultset to contain the corresponding model class, just omit the columns, or explicitly define the table:

 $passengers = $this->modelsManager->createBuilder()
                ->columns('*') // you could omit this line
                ->from('App\Models\Passengers')
                ->where('first_name like :search: or last_name like :search:', ['search' => $search])
                ->limit(10)
                ->distinct(true)
                ->getQuery()
                ->execute();
edited Feb '18

My goal is to get distinct result only, by your solution the code returned all rows.

My example data:

|| title - first_name - last_name - post_code - address

-> Mr - Ali - Tala - 8798 - avs BLd.

-> Mr - Ali - Tala - 9897 - abs Av.

-> Mrs - Zahra - Brown - 9856 - Abs.

My expcted result:

-> Mr - Ali - Tala

-> Mrs - Zahra - Brown

Use groupBy?