Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to use PHQL in a view

I'm trying to make a MySQL query in my view with information I have in it, but that query needs to use "DISTINCT" so I can't use find(). The query is kind of like this

$query = new Phalcon\Mvc\Model\Query("SELECT distinct(id) FROM race where date='$_date");
$query->setDI($di);
$racing = $query->execute();
foreach ($racing as $row) 
{
    echo "the id is ", $row->id;
}

when a use this one i get an error that says Undefined variable: di Unexpected value type: expected object implementing Phalcon\DiInterface, null given

i also tried

 $query = $this->modelsManager->createQuery("SELECT distinct(id) FROM race where date='$_date");
 $racing = $query->execute();
 foreach ($racing as $row) 
 {
    echo "he id is ", $row->id;
 }

but then i get this error Using $this when not in object context

the other way i try was

$rows = Carrera::find(array("distinct" => "id", "date='$_date'"));
foreach ($rows as $row) 
{
    echo "the id is ", $row->id;
 }

after the query gives me the results i want to saved in a variable maybe an array or something so i can compare them later

thanks in advance for any help i'm kind of in a rush to finish this project



53.2k
Accepted
answer

Shouting in all caps doesn't get your question answered any faster :p. I've updated your post, and also added proper code formatting.

The quickest answer I can give is: if you're building and running a query in the view, then you're doing it wrong. That sounds harsh I know, but really - the whole concept of Model / View / Controller is to separate the logic properly. Building and running queries in the view completely violates that principle.

With that said - check the documentation. I believe Query() or createQuery() (or both) require you to pass $di as an argument.