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 run query inside a custom validator

Hi, I'm trying to make a custom validator to check if an email is already submited or not. for this I need to execute a query in my custom validator, How can I do that?

use Phalcon\Validation\Validator,
    Phalcon\Validation\ValidatorInterface,
    Phalcon\Validation\Message;

class Unique extends Validator implements ValidatorInterface
{

    public function validate($validator, $attribute)
    {
            // how to execute "SELECT * FROM myTable" here... 
    }

}

thanks.

The simplest way:

Class Unique extends Validator implements ValidatorInterface
{

    public function validate($validator, $attribute)
    {
        $user = Users::count(array(
            'conditions' => 'email = :email:',
            'bind' => array(
                'email' => '[email protected]'
            )
        ));
    }

}

If user with email [email protected] not exist $user equals 0. If email is not unique $user should be 1 or more.

what if the table under validation does not have any Model? I want to use Raw Query. how can I do that?

Thank you, but question is stil unanswered. How can I use Raw Queries inside a custom validator?

Here is an example of use raw sql in model: http://docs.phalconphp.com/en/latest/reference/phql.html#using-raw-sql

In validator you can use like this:

Class Unique extends Validator implements ValidatorInterface
{

    public function validate($validator, $attribute)
    {
        $result = Robots::findByRawSql(…);
    }

}
edited May '14

OK, your example is based on Model

I want to run queries without Model

// Instantiate the Query

$query = new Phalcon\Mvc\Model\Query("SELECT * FROM Cars", $this->getDI());

// Execute the query returning a result if any

$cars = $query->execute();

But this does not work, I think I need $di and inside a custom validator I can't use $this->getDI()



3.4k
Accepted
answer

Try this:

// Instantiate the Query

$query = new Phalcon\Mvc\Model\Query("SELECT * FROM Cars", \Phalcon\DI::getDefault());

// Execute the query returning a result if any

$cars = $query->execute();

if \Phalcon\DI::getDefault() will return the $di in my application , so I think it would work. for now I have another wierd problem, after running a query, even "SELECT 1+1", Apache restarts after 1-2 seconds...

Thank you.

Put issue about apache into new topic and paste the apache logs