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.

Query Builder with model in namespaces

Hello,

I have problem with query builder. My code:

$this->modelsManager->createBuilder()
                    ->from('\modules\user\model\Privilege')
                    ->where('roleId = :roleId:', ['roleId' => $role->id])
                    ->notInWhere('id', $donotRemoveIds)
                    ->getQuery()
                    ->execute()
                    ->delete();

I'm getting this error:

Phalcon\Mvc\Model\Exception: Can't obtain the model 'roleId' source from the _models list, when preparing: SELECT [\modules\user\model\Privilege].* FROM [\modules\user\model\Privilege] WHERE (roleId = :roleId:) AND (id NOT IN (:phi154:, :phi155:, :phi156:, :phi157:, :phi158:, :phi159:, :phi160:, :phi161:, :phi162:, :phi163:, :phi164:, :phi165:, :phi166:, :phi167:))

I tried to use:

->where('\modules\user\model\Privilege.roleId = :roleId:', ['roleId' => $role->id])

Error was:

Phalcon\Mvc\Model\Exception: Unknown model or alias 'modules\user\model\Privilege' (1), when preparing: SELECT [\modules\user\model\Privilege].* FROM [\modules\user\model\Privilege] WHERE (\modules\user\model\Privilege.roleId = :roleId:) AND (id NOT IN (:phi168:, :phi169:, :phi170:, :phi171:, :phi172:, :phi173:, :phi174:, :phi175:, :phi176:, :phi177:, :phi178:, :phi179:, :phi180:, :phi181:))

also tried:

->where('Privilege.roleId = :roleId:', ['roleId' => $role->id])

and got this error:

Phalcon\Mvc\Model\Exception: Unknown model or alias 'Privilege' (1), when preparing: SELECT [\modules\user\model\Privilege].* FROM [\modules\user\model\Privilege] WHERE (Privilege.roleId = :roleId:) AND (id NOT IN (:phi182:, :phi183:, :phi184:, :phi185:, :phi186:, :phi187:, :phi188:, :phi189:, :phi190:, :phi191:, :phi192:, :phi193:, :phi194:, :phi195:))

Can you tell me how to properly use query builder with model within namespace?



4.4k
Accepted
answer

Using the query builder the following way will work:

$this->modelsManager->createBuilder()
                    ->addFrom('\modules\user\model\Privilege', 'p')
                    ->where('p.roleId = :roleId:', ['roleId' => $role->id]);

You can set the alias for a model via addFrom()