Let's say I had one of many columns of data in an ng-grid like so:
Status
Open
Closed
Open
Closed
Pending
Pending
Closed
I can filter for just one, but can I have multiple filters using ng-grid? For example, filtering for 'Open' gives me back all the ones that are 'Open', but what if I wanted to get back both 'Open' and 'Closed'? So the result would be like:
Status
Open
Closed
Open
Closed
Closed
Thanks for any help!
Asuming that you are using PHP/MySQL on your server side I would use this approach:
Enter something like Open|Closed in the filter input. (or use any separator you like)
This search string will be send to your server.
At the server explode() this search string into an array.
$search=explode("|",$searchstring);
Then generate a sql query from that array.
Example code:
//The searchstring that was send via ajax
$searchstring="Open|Closed";
//The field in the DB you want to filter
$field="status";
//Generate the where condition
$search=explode("|",$searchstring);
$whereCond="";
while (list($key, $val) = each($search)) {
$whereCond.= "`".$field."` ='".$val."' OR " ;
}
//remove the last unnecessary OR
$whereCond = substr_replace( $whereCond, "", -3 );
//Generate the query
$query="SELECT * FROM `table` WHERE ( ".$whereCond." )";
//Fetch data from the DB and return it to your App
This should generate a query like:
SELECT * FROM `table` WHERE ( `status` ='Open' OR `status` ='Closed' )
This way you can enter as many OR conditions as you want.
Watch out for the proper amount of spaces and use the correct quotes for the query.
In case you are using another stack, you have to figure out your own query generator. But basically it comes down to this approach. If you are using server sided data you have to do the filtering on the server side.
A client sided example can be found on the official ng-grid site here.
The Server-Side Paging Example is in fact client sided, it just fetches a large json file from the server.
Related
I'm currently using a database where I'll be sending 10 unique Id's at a time and I'm expecting a list of objects in return.
Is there any way where I can use a native query to get this.
select * from tbl_bank_customer_accounts where uid in ('05b6864b-ad10-4efe-af8d-b556e02dfc75','19226ae6-72f3-40dc-a690-079c979a3044','1a196c99-007f-4edd-a8a1-556f070cc852' ,'1e88f4fb-101c-4f6c-acd0-100bd1d02237' ,'20511b9b-8e7b-44fb-ba79-5c2103679b39' ,'3564b980-59e3-411f-8cc2-1bffa3cf9883' ,'4491b692-b6a4-4581-b150-411ab03151a4' ,'6364b0eb-015c-422f-a5e2-ae00828c70d6' ,'6ed7a6a2-265d-4d59-8764-d7742296aa17' ,'93c99403-d099-401f-a544-44984dcfc925');
the above one is my query can it be implemented using stored procedure
I am trying pagination feature in my project, I am using react with firebase.
My problem statement: if I have around 50 records in my database, what is the query if we want to select records 3 - 8?
If you want to use specific fields in front-end side then use slice and i think you can return your all list from backend and just slice from ui side.
let arr = [
{id:1,name:'One'},
{id:2,name:'Two'},
{id:3,name:'Three'},
{id:4,name:'Four'},
{id:5,name:'Five'},
{id:6,name:'Six'},
{id:7,name:'Seven'},
{id:8,name:'Eight'},
{id:9,name:'Nine'},
{id:10,name:'Ten'}
]
let selected = arr.slice(2,8);
console.log(selected)
Firebase Realtime Database doesn't have numeric index pagination. The API allows you to start at the beginning and page through the query results using startAt(), limitToFirst(), and other related methods, as described in the documentation.
If you absolutely must use indexes, you will have to read the entire set of results, populate an array, and pick out the desired results from that array using the indexes you want on the page.
I have encoded data
"{\"brand\":\"newBrand\",\"Id\":\"1\",\"field\":\"1\",\"date\":1437487498449,\"period\":2,\"newUser\":0}"
which I publish with command: PUBLISH channel "{\"brand\":\"newBrand\",\"Id\":\"1\",\"field\":\"1\",\"date\":1437487498449,\"period\":2,\"newUser\":0}"
Then I retrieve these data (Node.js) and successfully show them on the frontend (Angular) in one line as a message.
I want to show them in table(UI grid) - (column1 - Id, column2 - brand etc.)
Is there a way to parse these data to show them separately (every piece of data in appropriate column) in the table?
In angular, to display data in a table you can use 'ng-repeat'.For details go through this URL:http://www.w3schools.com/angular/angular_tables.asp
Use JSON.parse then use ng-repeat
var parsedData = JSON.parse("{\"brand\":\"newBrand\",\"Id\":\"1\",\"field\":\"1\",\"date\":1437487498449,\"period\":2,\"newUser\":0}")
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_tables_simple
I am trying to start using EF6 for a project. My database is already filled with millions of records.
I can't find right explanation how does EF send T-SQL to SQL Server? I am afraid that I am going to download bunch of data to user for no reason.
In code below I have found three way to get my data to List<> but I am not sure which is right way to do WHERE clause at SQL.
I do not want to fill client with millions of record and to query (filter) that data at client.
using (rgtBaza baza = new rgtBaza())
{
var t = baza.Database.SqlQuery<CJE_DOC>("select * from cje_doc where datum between #od and #do",new SqlParameter("od", this.dateTimePickerOD.Value.Date ) ,new SqlParameter("do", this.dateTimePickerOD.Value.Date)).ToList();
var t = baza.CJE_DOC.Where(s => s.DATUM.Value >= this.dateTimePickerOD.Value.Date && s.DATUM.Value <= this.dateTimePickerDO.Value.Date).ToList();
var query = from b in baza.CJE_DOC
where b.DATUM >= this.dateTimePickerOD.Value.Date && b.DATUM.Value <= this.dateTimePickerDO.Value.Date
select b;
var t = query.ToList();
this.dataGridViewCJENICI.DataSource = t;
}
In all 3 cases, the filtering will happen on the database side, the filtering (or WHERE clause) will not take place on the client side.
If you want to verify that this is true, especially for your last 2 options, add some logging so that you can see the generated SQL:
baza.Database.Log = s => Console.WriteLine(s);
In this case, since you are using EF already, choose the 2nd or 3rd options, they are both equivalent with different syntax. Pick your favorite syntax.
In all of those examples, EF6 will generate a SQL query including the where clause - it won't perform the where clause on the client.
It won't actually retrieve any data from the database until you iterate through the results, which in the examples above, is when you call .ToList().
EF6 would only run the filter on the client if you called something like:
baza.CJE_DOC.ToList().Where(x => x.Field == value)
In this instance, it would retrieve the entire table when you called ToList(), and then use a client-side Linq query to filter the results in the where clause.
Any of the 3 will run the query on the SQL Server.
EF relies on LINQ's deferred execution model to build up an expression tree. Once you take an action that causes the expression to be enumerated (e.g. calling ToList(), ToArray(), or any of the other To*() methods), it will convert the expression tree to SQL, send the query to the server, and then start returning the results.
One of the side effects of this is that when using the query or lambda syntax, expressions that EF does not understand how to convert to SQL will cause an exception.
If you absolutely need to use some code that EF can't handle, you can break your code into multiple segments -- filtering things down as far as possible via code that can be converted to SQL, using the AsEnumerable() method to "close off" the EF expression, and doing your remaining filtering or transformations using Linq to Objects.
I'm writing an NHibernate criteria that selects data supporting paging. I'm using the COUNT(*) OVER() expression from SQL Server 2005(+) to get hold of the total number of available rows, as suggested by Ayende Rahien. I need that number to be able to calculate how many pages there are in total. The beauty of this solution is that I don't need to execute a second query to get hold of the row count.
However, I can't seem to manage to write a working criteria (Ayende only provides an HQL query).
Here's an SQL query that shows what I want and it works just fine. Note that I intentionally left out the actual paging logic to focus on the problem:
SELECT Items.*, COUNT(*) OVER() AS rowcount
FROM Items
Here's the HQL:
select
item, rowcount()
from
Item item
Note that the rowcount() function is registered in a custom NHibernate dialect and resolves to COUNT(*) OVER() in SQL.
A requirement is that the query is expressed using a criteria. Unfortunately, I don't know how to get it right:
var query = Session
.CreateCriteria<Item>("item")
.SetProjection(
Projections.SqlFunction("rowcount", NHibernateUtil.Int32));
Whenever I add a projection, NHibernate doesn't select item (like it would without a projection), just the rowcount() while I really need both. Also, I can't seem to project item as a whole, only it's properties and I really don't want to list all of them.
I hope someone has a solution to this. Thanks anyway.
I think it is not possible in Criteria, it has some limits.
You could get the id and load items in a subsequent query:
var query = Session
.CreateCriteria<Item>("item")
.SetProjection(Projections.ProjectionList()
.Add(Projections.SqlFunction("rowcount", NHibernateUtil.Int32))
.Add(Projections.Id()));
If you don't like it, use HQL, you can set the maximal number of results there too:
IList<Item> result = Session
.CreateQuery("select item, rowcount() from item where ..." )
.SetMaxResult(100)
.List<Item>();
Use CreateMultiCriteria.
You can execute 2 simple statements with only one hit to the DB that way.
I am wondering why using Criteria is a requirement. Can't you use session.CreateSQLQuery? If you really must do it in one query, I would have suggested pulling back the Item objects and the count, like:
select {item.*}, count(*) over()
from Item {item}
...this way you can get back Item objects from your query, along with the count. If you experience a problem with Hibernate's caching, you can also configure the query spaces (entity/table caches) associated with a native query so that stale query cache entries will be cleared automatically.
If I understand your question properly, I have a solution. I struggled quite a bit with this same problem.
Let me quickly describe the problem I had, to make sure we're on the same page. My problem came down to paging. I want to display 10 records in the UI, but I also want to know the total number of records that matched the filter criteria. I wanted to accomplish this using the NH criteria API, but when adding a projection for row count, my query no longer worked, and I wouldn't get any results (I don't remember the specific error, but it sounds like what you're getting).
Here's my solution (copy & paste from my current production code). Note that "SessionError" is the name of the business entity I'm retrieving paged data for, according to 3 filter criterion: IsDev, IsRead, and IsResolved.
ICriteria crit = CurrentSession.CreateCriteria(typeof (SessionError))
.Add(Restrictions.Eq("WebApp", this));
if (isDev.HasValue)
crit.Add(Restrictions.Eq("IsDev", isDev.Value));
if (isRead.HasValue)
crit.Add(Restrictions.Eq("IsRead", isRead.Value));
if (isResolved.HasValue)
crit.Add(Restrictions.Eq("IsResolved", isResolved.Value));
// Order by most recent
crit.AddOrder(Order.Desc("DateCreated"));
// Copy the ICriteria query to get a row count as well
ICriteria critCount = CriteriaTransformer.Clone(crit)
.SetProjection(Projections.RowCountInt64());
critCount.Orders.Clear();
// NOW add the paging vars to the original query
crit = crit
.SetMaxResults(pageSize)
.SetFirstResult(pageNum_oneBased * pageSize);
// Set up a multi criteria to get your data in a single trip to the database
IMultiCriteria multCrit = CurrentSession.CreateMultiCriteria()
.Add(crit)
.Add(critCount);
// Get the results
IList results = multCrit.List();
List<SessionError> sessionErrors = new List<SessionError>();
foreach (SessionError sessErr in ((IList)results[0]))
sessionErrors.Add(sessErr);
numResults = (long)((IList)results[1])[0];
So I create my base criteria, with optional restrictions. Then I CLONE it, and add a row count projection to the CLONED criteria. Note that I clone it before I add the paging restrictions. Then I set up an IMultiCriteria to contain the original and cloned ICriteria objects, and use the IMultiCriteria to execute both of them. Now I have my paged data from the original ICriteria (and I only dragged the data I need across the wire), and also a raw count of how many actual records matched my criteria (useful for display or creating paging links, or whatever). This strategy has worked well for me. I hope this is helpful.
I would suggest investigating custom result transformer by calling SetResultTransformer() on your session.
Create a formula property in the class mapping:
<property name="TotalRecords" formula="count(*) over()" type="Int32" not-null="true"/>;
IList<...> result = criteria.SetFirstResult(skip).SetMaxResults(take).List<...>();
totalRecords = (result != null && result.Count > 0) ? result[0].TotalRecords : 0;
return result;