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

Simple SQL query

Hello guys... Here is the thing.

I want do a simple sql query like 'select id from table where x=y' but with phql everything is treated like an object, but I do not need this, there's any way to do a simple query using the default connection?



12.1k
  1. you can use ->toArray() to get an array from an object
  2. you can try $model->getModelsManager()->getReadConnection()
  3. you can try Phalcon\Mvc\Model\Query, but specify columns (not *), this should return a non-object result

I was doing it like on your 3rd point... but it returns me this:

Column 'referer_id' doesn't belong to any of the selected models (2), when preparing: SELECT referer_id FROM user WHERE name = :name:

This because it tries to insert it into the model structure, but I just want an id, don't need the model.



12.1k

Specify classname, not a table name in the query. Project\Model\User, for example

Okay, it did work... But it still using the model internally which increases the server load...

Thanks anyway.

Raw queries are what I was looking for, thanks!

Can I use raw sql in one model to extract data from multiple tables/models? for example, can i run this query inside moldel location, but also exctract from user_location?

$sql = "SELECT location.* FROM location WHERE NOT EXISTS (SELECT user_location.location_id FROM user_location WHERE user_location.user_id = '". $id ."' and user_location.location_id = location.id )";