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

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.



19.9k

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



19.9k

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: https://docs.phalcon.io/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(…);
    }

}


19.9k
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()



5.2k
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();


19.9k

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