CakePHP Find - Order By String-To-Int? - mysql

I want to use CakePHP to pull an array of photos from a database, sorted by photo title (0, 1, 2, 3...) My query currently looks something like:
$ss_photos = $this->Asset->find('all',array(
'conditions'=>array('kind'=>'photo'),
'order'=>'title'
));
Unfortunately the titles seem to be in string format, leading to an undesirable sort order (2.jpg after 19.jpg, etc). Is there a quick way to cast 'title' as an int for ordering purposes within a Cake query of this type?

Not sure if this is "recommended practice", but on a first pass it seems to work:
$ss_photos = $this->Asset->find('all',array(
'conditions'=>array('kind'=>'photo'),
'order'=>'Asset.title + 0'
));
Any opinions?

The solution is to create a hidden column which is responsible for orders in your example image names should be: 00002.jpg, 00019.jpg - this way the order will work properly.
If the results are not too many, I think it's easier to sort them in PHP (if you use it of course :)) See this natsort() you just need to extract a list of images and to sort them.

Related

How avoid infinity composed indexes in firestores

I'm doing a social media and in my posts i have 'tags' (which are practical infinity, as they are more then 200), i want my users to filter both tags and date, example:
myRef.where("tag" == "tagName").orderBy('date', 'asc')
BUT... I do have infinity number of tagNames, which give me a shock and i couldn't handle.
Should i create a custom map with sections of 1m size ???
Should i create a custom ID with data on it???
How will i be able to mix data asc with these queries or mix two or more types together?
The query you have requires an index on tag + date, not on tagName + date.
But if you want to keep a list of tags for each document, you'll want to store those in an array, and then use array-contains to check whether the document has a certain tag. To see if tagName exists in the array of String values tag, you'd query for:
myRef.where("tag", "array-contains", "tagName").orderBy('date', 'asc')
For more on this, see Better Arrays in Cloud Firestore!

Rails, MySql, JSON column which stores array of UUIDs - Need to do exact match

I have a model called lists, which has a column called item_ids. item_ids is a JSON column (MySQL) and the column contains array of UUIDs, each referring to one item.
Now when someone creates a new list, I need to search whether there is an existing list with same set of UUIDs, and I want to do this search using query itself for faster response. Also use ActiveRecord querying as much as possible.
How do i achieve this?
item_ids = ["11E85378-CFE8-39F8-89DC-7086913CFD4B", "11E85354-304C-0664-9E81-0A281BE2CA42"]
v = List.new(item_ids: item_ids)
v.save!
Now, how do I check whether a list exists which has item ids exactly matches with that mentioned in query ? Following wont work.
list_count = List.where(item_ids: item_ids).count
Edit 1
List.where("JSON_CONTAINS(item_ids, ?) ", item_ids.to_json).count
This statement works, but it counts even if only one of the item matches. Looking for exact number of items.
Edit 2
List.where("JSON_CONTAINS( item_ids, ?) and JSON_LENGTH(item_ids) = ?", item_ids.to_json, item_ids.size).count
Looks like this is working
You can implement a has many relation between lists and items and then access like this.
List.includes(:item).where('items.id in (?)',item_ids)
To implement has_many relation:
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

yii pagination issue trying to use 2 criterias

Disclaimer I'm self taught. Got my rudimentary knowledge of php reading forums. I'm an sql newb, and know next to nothing about yii.
I've got a controller that shows the products on our webstore. I would like the out of stock products to show up on the last pages.
I know I could sort by stock quantity but would like the in stock products to change order every time the page is reloaded.
My solution (probably wrong but kinda works) is to run two queries. One for the product that has stock, sorted randomly. One for the out of stock product also ordered randomly. I then merge the two resulting arrays. This much has worked using the code below (although I feel like there must be a more efficient way than running two queries).
The problem is that this messes up the pagination. Every product returned is listed on the same page and changing pages shows the same results. As far as I can tell the pagination only works for 1 CDbCriteria at a time. I've looked at the yii docs for CPagination for a way around this but am not getting anywhere.
$criteria=new CDbCriteria;
$criteria->alias = 'Product';
$criteria->addCondition('(inventory_avail>0 OR inventoried=0)');
$criteria->addCondition('Product.parent IS NULL');
$criteria->addCondition('web=1');
$criteria->addCondition('current=1');
$criteria->addCondition('sell>sell_web');
$criteria->order = 'RAND()';
$criteria2=new CDbCriteria;
$criteria2->alias = 'Product';
$criteria2->addCondition('(inventory_avail<1 AND inventoried=1)');
$criteria2->addCondition('Product.parent IS NULL');
$criteria2->addCondition('web=1');
$criteria2->addCondition('current=1');
$criteria2->addCondition('sell>sell_web');
$criteria2->order = 'RAND()';
$crit1=Product::model()->findAll($criteria);
$crit2=Product::model()->findAll($criteria2);
$models=array_merge($crit1,$crit2);
//I know there is something wrong here, no idea how to fix it..
$count=Product::model()->count($criteria);
$pages=new CPagination($count);
//results per page
$pages->pageSize=30;
$pages->applyLimit($criteria);
$this->render('index', array(
'models' => $models,
'pages' => $pages
));
Clearly I am in over my head. Any help would be much appreciated.
Edit:
I figured that a third CDbCriteria that includes both the in stock and out of stock items could be used for the pagination (as it would include the same number of products as the combined results of the first 2). So I tried adding this (criteria1 and criteria2 remain the same):
$criteria3=new CDbCriteria;
$criteria3->alias = 'Product';
//$criteria3->addCondition('(inventory_avail>0 OR inventoried=0)');
$criteria3->addCondition('Product.parent IS NULL');
$criteria3->addCondition('web=1');
$criteria3->addCondition('current=1');
$criteria3->addCondition('sell>sell_web');
//$criteria3->order = 'RAND()';
$crit1=Product::model()->findAll($criteria);
$crit2=Product::model()->findAll($criteria2);
$models=array_merge($crit1,$crit2);
$count=Product::model()->count($criteria3);
$pages=new CPagination($count);
//results per page
$pages->pageSize=30;
$pages->applyLimit($criteria3);
$crit1=Product::model()->findAll($criteria);
$crit2=Product::model()->findAll($criteria2);
$models=array_merge($crit1,$crit2);
$this->render('index', array(
'models' => $models,
'pages' => $pages
));
I'm sure I'm missing something super obvious here... Been searching all day getting nowhere.
So you are running into what is IMO one of the potential drawbacks of natural language query builder frameworks. They can get your thinking on how you might approach a SQL problem going down a bad path when trying to work with the "out of the box" methods for building queries. Sometimes you might need to think about using raw SQL query capabilities that most every framework to provide in order to best address your problem.
So let's start with the basic SQL for how I would suggest you approach your problem. You can either work this into your query builder style (if possible) or make a raw query.
You could easily form a calculated field representing binary inventory status for sorting. Then also sort by another criteria secondarily.
SELECT
field1,
field2,
/* other fields */
IF(inventory_avail > 0, 1, 0) AS in_inventory
FROM product
WHERE /* where conditions */
ORDER BY
in_inventory DESC, /* sort items in inventory first */
other_field_to_sort ASC /* other sort criteria */
LIMIT ?, ? /* pagination row limit and offset */
Note that this approach only returns the rows of data you need to display. You move away from your current approach of doing a lot of work in the application to merge record sets and such.
I do question use of RAND() for pagination purposes as doing so will yield products potentially appearing on one page after another as the user paginates through the pages, with other products perhaps not showing up at all. Either that or you need to have some additional complexity added to your applicatoin to somehow track the "randomized" version of the entire result set for each specific user. For this reason, it is really unusual to see order randomization for paginated results display.
I know you mentioned you might like to spike out a randomized view to the user on a "first page". If this is a desire that is OK, but perhaps you decouple or differentiate that specific view from a wider paginated view of the product listing so as to not confuse the end user with a seemingly unpredictable pagination interface.
In your ORDER BY clause, you should always have enough sorting conditions to where the final (most specific) condition will guarantee you a predictable order result. Oftentimes this means you have to include an autoincrementing primary key field, or similar field that provides uniqueness for the row.
So let's say for example I had the ability for user to sort items by price, but you still obviously wanted to show all inventoried items first. Now let's say you have 100K products such that you will have many "pages" of products with a common price when ordered by price
If you used this for ordering:
ORDER BY in_inventory DESC, price ASC
You could still have the problem of a user seeing the same product repeated when navigating between pages, because a more specific criteria than price was not given and ordering beyond that criteria is not guaranteed.
You would probably want to do something like:
ORDER BY in_inventory DESC, price ASC, unique_id ASC
Such that the order is totally predictable (even though the user may not even know there is sorting being applied by unique id).

Sorted array with specific items on top using Zend_Db_Select order()

I am trying to modify a plug-in that, among other things, alphabetically sorts an array from a mysql database. The part of the relevant PHP file that does the sorting looks like this:
$select->order("$alias.name ASC");
I want to continue to sort the items in ascending order, but I want to keep a specific item at the top (out of its alphabetical order).
From the information here it looks like the way to do this in MySQL would be simple, just:
ORDER BY name = 'Library' desc,
name asc;
But even studying the information here, I can't quite translate this into the order() function. I have tried:
$select->order("$alias.name ='Library' DESC","$alias.name ASC")
But it seems that it does not work quite that way.
Alright, found the answer-
I needed to use Zend_Db_Expr(). In case it is helpful to anyone else, this was solved like so:
$select->order(array(
new Zend_Db_Expr("$alias.name = 'Library' DESC"),
new Zend_Db_Expr("$alias.name ASC")
));

Multiple databases, possibly creating a loop?

I have the following code below...the query works, but I'm looking for a better way to search though an entire column for a specific criteria. I think my question is going to require a loop, I'm just not sure how to perform it.
The last line of code states '
Where [dbIdwWhseLC].[dbo].[tbItemTxt].[sTxt] like '%258912.pdf
The value 258912.pdf is the value in
[IDEAUrlBot].[dbo].[IDEA Project Tracker].[Filename]
I would like to try and create a method where the query reads one value in sTxt, then compares the whole column to Filename. If it finds the value, then display sTxt, if not, go to the next value in sTxt and begin searching each value in Filename.
Please let me know if you need additional information. Thanks in advance.
Select [dbIdwWhseLC].[dbo].[tbItemTxt].[nItemId]
, [sTxtType]
, [IDEAUrlBot].[dbo].[tbl_IDWItems].[nUrlId]
, [IDEAUrlBot].[dbo].[tbl_Urls].[sUrl]
, [sTxt]
, [Filename]
, [dbIdwWhseLC].[dbo].[tbItemTxt].[vUpdateDt]
From [dbIdwWhseLC].[dbo].[tbItemTxt]
Left Join [IDEAUrlBot].[dbo].[tbl_IDWItems] on [dbIdwWhseLC].[dbo].[tbItemTxt].[nItemid] = [IDEAUrlBot].[dbo].[tbl_IDWItems].[nItemid]
Join [IDEAUrlBot].[dbo].[tbl_Urls] on [IDEAUrlBot].[dbo].[tbl_IDWItems].[nUrlId] = [IDEAUrlBot].[dbo].[tbl_Urls].[nUrlId]
Join [IDEAUrlBot].[dbo].[IDEA Project Tracker] on [IDEAUrlBot].[dbo].[tbl_IDWItems].[nUrlId] = [IDEAUrlBot].[dbo].[IDEA Project Tracker].[UrlId]
Where [dbIdwWhseLC].[dbo].[tbItemTxt].[sTxt] like '%258912.pdf'
If I understand you correctly, it ought to be possible to do this:
select itemTxt.[nItemId]
, [sTxtType]
, idwItems.[nUrlId]
, urls.[sUrl]
, [sTxt]
, [Filename]
, itemTxt.[vUpdateDt]
From [dbIdwWhseLC].[dbo].[tbItemTxt] as itemTxt
Left Join [IDEAUrlBot].[dbo].[tbl_IDWItems] as idwItems
on itemTxt.[nItemid] = idwitems.[nItemid]
Join [IDEAUrlBot].[dbo].[tbl_Urls] as urls
on idwItems.[nUrlId] = urls.[nUrlId]
Join [IDEAUrlBot].[dbo].[IDEA Project Tracker] projTracker
on itemText.[nUrlId] = projTracker.[UrlId]
Where itemTxt.[sTxt] like '%258912.pdf' -- not sure you intend this to remain
and projTracker.[FileName] = itemTxt.[sTxt]
But that's so simple that there must be some aspect to what you're looking for that's not clear to me.
Do you want to stop searching after you find a match between [FileName] and [sTxt]? If you want to return exactly one record, you can just change the first line to
select top 1 itemTxt.[nItemId]
... and add an ORDER BY clause to the end to control how the results are sorted and therefore which one is the "top 1".
Do you need to use wildcards when matching [FileName] and [sTxt]? It's not clear to me from the description which column would have the full path (or file name) and which would have just "258912.pdf", but you could change my last line to:
itemTxt.[sTxt] like ('%' + projTracker.[FileName])
If you need something more complex, like the first record from itemTxt.[sTxt] that matches projTracker.[FileName] for every record in projTracker, please say so in the comments.
If none of this is along the lines of what you need, you'll need to elaborate on what it is you do need. Please add more detail to your question, such as an example of what the output should look like or what you plan to do with it.