Troubles with IN in Yii query builder - mysql

I use Yii Framework and i need to build difficult query with many conditions.
I'm filling 2 arrays $conditions and $values.
And i have one problem.
Below is example
When i use
$usersId = '1,2';
$conditions[] = 'e.user_id IN(:usersId)';
$values[':usersId'] = $usersId;
I get only value from user_id = 1
When i'm not use option and write manually
$usersId = '1,2';
$conditions[] = 'e.user_id IN(' . $usersId . ')';
no problem.
Of course i can use second construction, but it seems not very good.

You should addInCondition
$criteria->addInCondition('e.user_id',array(1,2));

Yii way would be to use CDbCriteria addInCondition function
$usersId = array(1,2); //must be array
$criteria=new CDbCriteria();
$criteria->addInCondition('user_id',$usersId);
$result = MyModel::model()->findAll($criteria);

$values[':usersId'] = $usersId;
If I understand your wuestion correctly, you can use the BindParam function in yii?
Instead of this - $values[':usersId'] = $usersId;
Write this - $command->BindParam(':usersId', $usersId, PDO::PARAM_STR);
Very simply, you're binding your parameters to your command statement.
Hope it works!

Related

Laravel 4.x, Eloquent multiple conditions

I've tried to this:
Product::where(['product_id' => $product->id, 'catalog_id' => $key])->first();
This isn't working at all. When I'm doing this:
Product:where('product_id', $product->id)->where('catalog_id', $key)->first();
It just works fine. I've searched in the documentation of Laravel,
and found nothing.
Is there any option to using the where function with an array in it ?
You need to use where() individually. If you want to dynamically building the query you can do something like:
$wheres = array('product_id' => $product->id, 'catalog_id' => $key);
$q = new Product;
foreach ( $wheres as $k => $v ) {
$q = $q->where($k, $v);
}
$products = $q->first();
In fact we were all wrong ;)
As of latest version of the framework you can do exactly what you wanted.
Check this commit and update Laravel if you need that feature.
https://github.com/laravel/framework/commit/87b267a232983abdac7c23c2dc6b1b270dd24b8a
Product::whereNested(function($query) use ($key, $product){
$query->where('product_id', $product->id);
$query->where('catalog_id', $key);
})->get();
Laravel's wheres use an and condition by default:
$products = Product::where('this','=','that')->where('something','=','hello')->get();
is somewhat equivalent to:
SELECT * FROM products WHERE this = 'that' AND something = 'hello';
You simply chain the ->where() methods together. No need for an array.
If you want to use an or condition:
$products = Product::where('this','=','that')->orWhere('something','=','hello')->get();

zf2 db sql where datetime before two ours ago

I'm looking for the right zf2 syntax to select timestamps / timeranges from the database. I know how to make where statements. However it seems that greaterThan() and lessThan() are not working with timestamps/datetime:
where = new Where();
$where->lessThan("datecolumn",$vardate);
I want to select all records older than 2 hours. so whats the right way to select date with zend framework 2?
Thx, I really appreciate your help
This works fine (just a sample) -
$select = new Select('album');
$created = date('Y-m-d H:i:s', strtotime("-2 hours"));
$where = new Where();
$where->lessThanOrEqualTo('created', $created);
$select->where($where);
$resultSet = $this->tableGateway->selectWith($select);
Try something like this in your mapper method:
$selectRecords = $this->tableGateway->getSql()->select();
$selectRecords->columns(array('id'))
->where->greaterThanOrEqualTo('dateColumn', $startDate)
->lessThanOrEqualTo('dateColumn', $endDate)
;
$resultSet = $this->tableGateway->selectWith($selectRecords);

Print Sql query in Symfony

I need to findout the normal sql query for the below. Can you guys please suggest me how can i achieve in Symfony.
Example:
$r = Doctrine_Query::create()
->select('u.worked_hours')
->from('tasksComments u')
->where('u.tasks_id = ?', $arr_values['tasks_id'])
->andwhere('u.id != ?', $arr_values['id'])
->andwhere('u.created_at LIKE ?', $date."%");
$results1 = $r->execute();
On the query object, use the method getSQL.
In your case:
$r = Doctrine_Query::create()
->select('u.worked_hours')
->from('tasksComments u')
->where('u.tasks_id = ?', $arr_values['tasks_id'])
->andwhere('u.id != ?', $arr_values['id'])
->andwhere('u.created_at LIKE ?', $date."%");
var_dump($r->getSQL()); // print the SQL query - you will need to replace the parameters in the query
var_dump($r->getParams()); // print the parameters of the query so you can easily replace the missing parameters in the query
Note that I don't know the namespace of Doctrine_Query but I am assuming that your Query object in this Query object in the Doctrine API documentation.
Using Symfony 1.4 with Doctrine 1.2.3
echo $q->getSqlQuery();
You can view all the executed queries in the profiler toolbar by clicking on the db panel icon (the last section of the toolbar) then on the [Display runnable query] link under your query.

Joomla Database - How to use LIMIT in getQuery?

I want to build the below query using joomla inbuilt database class.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This is the query I have built up to now.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));
$db->setQuery($query);
$rows = $db->loadObjectList();
I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks
Older than Joomla 3.0
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from($db->nameQuote('#__table_name'))
->order($db->nameQuote('id').' desc');
$db->setQuery($query,0,1);
$rows = $db->loadObjectList();
$db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.
Newer than Joomla 3.0
setLimit(integer $limit, integer $offset)
If you want just one row
$query->setLimit(1);
Read more
This should work as well:
$query->setLimit(1);
Documentation: http://api.joomla.org/cms-3/classes/JDatabaseQueryLimitable.html
SetLimit doesn't work for me in Joomla 3.4.x, so try:
Within the model:
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
$query->from('#__your_table');
$this->setState('list.limit', 0); // 0 = unlimited
return $query;
}
Davids answer: https://joomla.stackexchange.com/questions/4249/model-getlistquery-fetch-all-rows-with-using-jpagination
Run that before the model calls getItems and it will load all the
items for you.
A few caveats with this.
You can also do this outside the model, so if for instance you were in
your view. You could do the following:
$model = $this->getModel(); $model->setState('list.limit', 0);
Sometimes you can do this too early, before the model's state has been
populated, which will cause the model to get rebuilt from the user
state after you have set the limit, basically overriding the limit.
To fix this, you can force the model to populate its state first:
$model = $this->getModel(); $model->getState();
$model->setState('list.limit', 0); The actual populateState method is
protected, so outside the model you can't call it directly, but any
call to getState will make sure that the populateState is called
before returning the current settings in the state.
Update: Just had to revisit this answer, and I can confirm, both the methods
setLimit & order are working if used as below.
$query->order($db->qn($data->sort_column_name) . ' ' . $data->sort_column_order);
$query->setLimit($length,$start);
OLD ANSWER
As of 08/Sept/14 The solutions from #Dasun or #escopecz arent working for me on J3.x
but this old trick is working for me which is nice,
$query->order($db->qn('id') . ' DESC LIMIT 25');
And About your specific requirement of wishing to fetch only 1 row you could use :
$rows = $db->loadObject();

Chaining orX in Doctrine2 query builder

I have to dynamically add OR expressions to the query builder returned by getListQueryBuilder, right after adding a where clause. I can't find any suitable way of doing this, i'm just started learning Doctrine.
How can i "chain" a given number of orX and add them to my builder?
public function getListQueryBuilder($ownerId)
{
$qb = $this->createQueryBuilder('t');
return $qb
->where($qb->expr()->eq('t.user', ':user'))
->setParameter('user', $ownerId);
}
$builder = getListQueryBuilder(4);
// $ORs is a dynamically builded array, here is just an example
$ORs = array();
$ORs[] = $builder->expr()->like("t.name", 'my name');
$ORs[] = $builder->expr()->like("t.description", 'desc');
// Adding ORs to the builder
$builder->andWhere($builder->expr()->orX(/* here */));
You can check this solution:
$orX = $builder->expr()->orX();
foreach($ORs as $or) {
$orX->add($or);
}
$builder->andWhere($orX);
I stumbled on the same problem and tried :
$builder->andWhere($builder->expr()->orX($ORs));
but it does not work since orX calls "return new Expr\Orx(func_get_args());" internally and you end up with something like array(array(or1, or2))
having looked at the API however i figured you can do this:
$builder->andWhere($builder->expr()->orX()->addMultiple($ORs));
OR do use $ORs table at all but issue:
$orx = $builder->expr()->orX();
$orx->add($builder->expr()->like("t.name", 'my name'));
$orx->add($builder->expr()->like("t.description", 'desc'));
$builder->andWhere($orx);