How to create cdbcriteria fo the query like :
select * from table_name where 'profile_type'='*'OR 'profile_type'=$usertype AND 'location'='*'OR 'location'=$country
you can try sth like this:
$criteria = new CDbCriteria;
$criteria->condition = "(profile_type='*' OR profile_type=:prof ) AND
(location='*' OR location=:loc ) ";
$criteria->params = array(':prof' => $usertype, ':loc' => $country);
$model = MyModel::model()->findAll($criteria );
You can directly pass condition as below.
Note: This is one of the method. Not an ultimate solution.
$criteria = new CDbCriteria;
$criteria->condition = "(profile_type ='*' OR profile_type = $usertype) AND (location ='*' OR location = $country)";
$model = Model_name::model()->findAll($criteria );
Related
I´ve got the following SQL-Query
$uidArray = explode(",", $uids);
foreach ($uidArray as $uid) {
$dynamicUid[] = '`uid` LIKE \''.$uid.'\'';
}
$query = $this->createQuery();
$query->statement("SELECT * FROM `tx_myextension_domain_model_thi` WHERE ".implode($dynamicUid, " OR "));
return $query->execute();
This works fine but I want to have it like this:
$uidArray = explode(",", $uids);
$query = $this->createQuery();
foreach ($uidArray as $key => $value) {
$constraints[] = $query->equals('uid', $value);
}
return $query->matching(
$query->logicalAnd($constraints)
)->execute();
Here I get the following Output with the Query Parser :
'SELECT `tx_myextension_domain_model_thi`.* FROM `tx_myextension_domain_model_thi`
`tx_myextension_domain_model_thi`
WHERE ((`tx_myextension_domain_model_thi`.`uid` = :dcValue1) AND
(`tx_myextension_domain_model_thi`.`uid` = :dcValue2)) AND
(`tx_myextension_domain_model_thi`.`sys_language_uid` IN (0, -1)) AND
(`tx_myextension_domain_model_thi`.`pid` = 0) AND
((`tx_myextension_domain_model_thi`.`deleted` = 0) AND (
`tx_myextension_domain_model_thi`.`t3ver_state` <= 0) AND
(`tx_myextension_domain_model_thi`.`pid` <> -1) AND
(`tx_myextension_domain_model_thi`.`hidden` = 0) AND
(`tx_myextension_domain_model_thi`.`starttime` <= 1607084460) AND
((`tx_myextension_domain_model_thi`.`endtime` = 0)
OR (`tx_myextension_domain_model_thi`.`endtime` > 1607084460)))'
And the Uids as dcValue-Array.
dcValue1 => '1' (1 chars)
dcValue2 => '2' (1 chars)
Maybe someone can help me to rewrite this, because unfortunately I can't get any further!
Thanks :)
Did you try the in operator?
public function yourFunctionName($uid)
{
$query = $this->createQuery();
$query->in('uid', $uidArray);
return $query->execute();
}
Assuming that your array looks like this:
$uidArray = [
0 = '34',
1 = '15',
3 = '88'
]
EDIT
If you do not care about where your objects are stored then you can do the following.
public function yourFunctionName($uid)
{
$query = $this->createQuery();
$query->getQuerySettings()->setRespectStoragePage(FALSE);
$query->matching(
$query->in('uid', $uidArray)
);
return $query->execute()];
}
Which is going to ignore the pid in the query
can someone help me convert this sql to symfony?
SELECT cl.* from computador_coleta cl inner join class_property p on cl.id_class_property = p.id_class_property where p.id_class = 15 AND cl.id_computador = 2510;
cl.id_computador is a variable.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT cc FROM CacicCommonBundle:ComputadorColeta cc INNER JOIN CacicCommonBundle:ClassProperty cp WITH cc.classProperty = cp.idClassProperty WHERE cp.idClass = 15 AND cc.computador = :id'
)->setParameter('id', $computador);
$result = $query->getResult();
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$result = $qb->select('c')
->from('CacicCommonBundle:ComputadorColeta','cc')
->innerJoin('cc.classProperty','cp')
->where('cp.idClass = :idClass')
->andWhere('cc.idComputador = :idComputador')
->setParameter('idClass', 15)
->setParameter('idComputador', 2510)
->getQuery()
->getOneOrNullResult();
if(!$result) {
throw new \Exception('no results')
}
I would recommend using something like this with doctrine as it is easier to read
I have the following:
public function search() {
$criteria = new CDbCriteria();
$criteria->compare('id',$this->id);
$criteria->compare('entity_id',$this->entity_id);
$criteria->compare('name',$this->name,true);
(etc...)
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
When I apply this:
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
the user can only see on CGridView is own records. Nice.
But, for some reason, the filter doesn't work.
If I comment those lines:
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
The filter works. But, obviously, the user will see ALL users records.
Update:
If instead of using condition and params properties I use compare() method, like this:
$criteria->compare('entity_id',$entity->id);
It works.
Why does it work with compare, and NOT with condition and params?
When you use this
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria->condition = 'entity_id=:entity_id';
$criteria->params = array(':entity_id'=>$entity->id);
}
what happens is the condition property is reset (due to the fresh assignment), the compare function you have used earlier appends the comparison to the the condition see http://www.yiiframework.com/doc/api/1.1/CDbCriteria#compare-detail for information on how this works, therfore when you do a fresh assignment it clears all the existing conditions.
Therefore Either you can use a new criteria object like below
if (Yii::app()->user->role == SiteUser::ROLE_AUTHOR) {
$userId = Yii::app()->user->getId();
$entity = Entity::model()->find("user_id = $userId");
$criteria2= new CDbCriteria();
$criteria2->condition = 'entity_id=:entity_id';
$criteria2->params = array(':entity_id'=>$entity->id);
$criteria->mergeWith($criteria2);
}
or you can move the logic for SiteUser::ROLE_AUTHOR before the compare statements
Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?
$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
->from(…)
->where(…);
$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);
$intermediate = $queryBuilder->getQuery()->parse();
$dialect = DI::getDefault()->get('db')->getDialect();
$sql = $dialect->select($intermediate);
Edit: As of 2.0.3 you can do it super simple, see comment for full details:
$modelsManager->createBuilder()
->from('Some\Robots')
->getQuery()
->getSql()
you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html
According to documentation you can get this way the resulting sql query.
Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements
$db = Phalcon\DI::getDefault()->getDb();
$sql = $db->getSQLStatement();
$vars = $db->getSQLVariables();
if ($vars) {
$keys = array();
$values = array();
foreach ($vars as $placeHolder=>$var) {
// fill array of placeholders
if (is_string($placeHolder)) {
$keys[] = '/:'.ltrim($placeHolder, ':').'/';
} else {
$keys[] = '/[?]/';
}
// fill array of values
// It makes sense to use RawValue only in INSERT and UPDATE queries and only as values
// in all other cases it will be inserted as a quoted string
if ((strpos($sql, 'INSERT') === 0 || strpos($sql, 'UPDATE') === 0) && $var instanceof \Phalcon\Db\RawValue) {
$var = $var->getValue();
} elseif (is_null($var)) {
$var = 'NULL';
} elseif (is_numeric($var)) {
$var = $var;
} else {
$var = '"'.$var.'"';
}
$values[] = $var;
}
$sql = preg_replace($keys, $values, $sql, 1);
}
More you can read there
The following is the common solution:
$result = $modelsManager->createBuilder()
->from(Foo::class)
->where('slug = :bar:', ['bar' => "some-slug"])
->getQuery()
->getSql();
But you might not expect to see the query without its values, like in:
die(print_r($result, true));
Array
(
[sql] => SELECT `foo`.`id`, `foo`.`slug` FROM `foo` WHERE `foo`.`slug` = :bar
[bind] => Array
(
[bar] => some-slug
)
[bindTypes] =>
)
So, this simple code might be useful:
public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
{
$data = $builder->getQuery()->getSql();
['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;
$finalSql = $sql;
foreach ($binds as $name => $value) {
$formattedValue = $value;
if (\is_object($value)) {
$formattedValue = (string)$value;
}
if (\is_string($formattedValue)) {
$formattedValue = sprintf("'%s'", $formattedValue);
}
$finalSql = str_replace(":$name", $formattedValue, $finalSql);
}
return $finalSql;
}
If you're using query builder then like given below then getPhql function can serve the purpose as per phalcon 3.4.4 version.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…)->getQuery();
$queryBuilder->getPhql();
if (!function_exists("getParsedBuilderQuery")) {
/**
* #param \Phalcon\Mvc\Model\Query\BuilderInterface $builder
*
* #return null|string|string[]
*/
function getParsedBuilderQuery (\Phalcon\Mvc\Model\Query\BuilderInterface $builder) {
$dialect = Phalcon\Di::getDefault()->get('db')->getDialect();
$sql = $dialect->select($builder->getQuery()->parse());
foreach ($builder->getQuery()->getBindParams() as $key => $value) {
// For strings work fine. You can add other types below
$sql = preg_replace("/:?\s?($key)\s?:?/","'$value'",$sql);
}
return $sql;
}
}
Simple function that im using for debugging.
i have w function called update that i want to update a specific record in database according to module id (m_id) and key (key)
here is the function
public function updateRecord($module,$key,$newData){
$id = $this->module($module);
$model = new Form;
$criteria = new CDbCriteria();
$criteria->condition = "`m_id` = 1 AND `key` = 'txt'";
// $model = Yii::app()->db->createCommand("SELECT * FROM `tbl_setting` WHERE `m_id` = 1 AND `key` = 'txt'")->query();
die(var_dump($model->findAll($criteria)));
// $model = Yii::app()->db->createCommand("SELECT * FROM `tbl_setting` WHERE `m_id` = 1 AND `key` = 'txt'")->execute();
$model->m_id = $id ;
$model->attributes = $newData;
$model->save();
//die(print_r($model['m_id']));
//if(isset($_POST['save'])){
//$model['m_id'] = $id;
//}
}
every time i try to use this function it give me error that $model is not an object so it can't execute
$model->m_id = $id ;
i check out the type of findAll() and it gives an array
i checkout all find() methods and only findByPk() that give an object
and i want to choose according to the $criteria and i don't know what to do any help ?! :)
findAll will always return an array. With objects if there are record found, or an empty array on no result. find only returns 1 record, or NULL if nothing is found:
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#find-detail
Your code will be save when you do it like this:
if(!is_null($model)) {
$model->m_id = $id ;
$model->attributes = $newData;
$model->save();
} else {
echo 'No record found';
}