I have tow tables where User (id,name) and UserInfo (user_id,email,date_edit)
How i can do SQL request to CoreData like
select * from user inner join userinfo on userinfo.user_id=user.id
Without using relationships bu CoreData?
Another example:
I want fetch max date_edit from userinfo table?
Instead of thinking in SQL and trying to translate that to Core Data, start with the problem you are trying to solve. Then, express that using Core Data relationships.
For example, if you wanted to get an array of emails for an array of users, you could just do something like:
NSArray *emailArray = [usersArray valueForKeyPath:#"userInfo.email"];
Core Data has aggregate functions. You might be able to do something simple with KVO like:
NSNumber *maxDateEdit = [userInfoArray valueForKeyPath:#"#max.date_edit"];
Otherwise, check out the section "Fetching Objects" here
Related
Is it possible to fetch all records of a table in bookshelf without a query?
I'v got a Model named Person, and I'd like to retrieve all of its records.
What I am doing currently is this:
Person.where('id', '>', 0) ).fetchAll()
.then((result) => {
// doing stuff
});
which just doesn't feel right.
I was hoping for something like
// using empty querybuilder
Person.query().fetchAll()
or
Person.all //
Am I missing something?
I suppose model.fetchAll is the thing you are looking for.
Simple helper function for retrieving all instances of the given model.
See the API Reference of Bookshelf.js
In this case, you can use Model.fetchAll(), which fetches a collection of models from the database, using any query parameters currently set on the model to form a select query.
My question is pretty simple. I am working on Kentico 9 with its SQL Server database which contains several tables which had been added directly from the SQL Management Studio by an external contractor. The fact is that those tables are being used to store custom content which will be displayed for a site, but, in the code they don't have the code for making queries. I mean, they don't have Info and Provider classes.
https://docs.kentico.com/display/K82/Retrieving+database+data+using+ObjectQuery+API
According with this, all tables into the Kentico database can be accessed by invoking methods on these classes, but I don't have it this time.
Something like this, it will not work if I use my table name:
var user = UserInfoProvider.GetUserInfo("administrator");
var items = CustomTableItemProvider.GetItems("MyTable")
.TopN(10)
.WhereEquals("ItemCreatedBy", user.UserID)
.OrderBy("ItemCreatedWhen");
My question is:
can I query any table by its name?
One last thing:
I cannot declared those table as "custom table" because it seems to be a bug in the CMS.
Or you can pull data using your own SQL query:
var ds = ConnectionHelper.ExecuteQuery("select ....", null, QueryTypeEnum.SQLQuery);
Nevertheless I would recommend to create a custom class inside a custom module (much more robust than custom tables) instead and use the generated Info and InfoProvider classes to get and manipulate data.
I think an object has to be registered within the system (created through Kentico UI or API) in order to be pulled from DB with object query.
So I'd choose one of the following options:
Use Entity Framework or something similar to work with that data
Create appropriate custom tables or even custom module and push data there. Not sure why you can't create a custom table... What is an error you're getting?
If you need to present data on the UI only (without processing on the back end) - use just custom queries
Hope this helps.
If you are accessing in code then you could do it the good old fashioned way. If you want to pull data from the database to display on the website you could also do so by creating a custom query and using a transformation to display the fields, then use a repeater on the page to display the transformed data. Alternatively you can use a SQL datasource with a basic repeater, but you still have to create a transformation to display the data. Both methods allow you to access the data in the tables from within the CMS UI, no need to touch any code behind.
If your objective is to read data from these database tables to transform on webpage e.g. using CMS Repeater webpart, you can simply create custom query(s) in Kentico itself and load data using it. You can find the detail here on how to create custom custom queries and load data using it.
On the other hand you can also write your custom classes and define the custom methods where you can pull data using your own SQL query like this:
var ds = ConnectionHelper.ExecuteQuery("select ....", null, QueryTypeEnum.SQLQuery);
Lastly I don't think there should be any issue to create custom table instead of those direct DB tables, only thing we have to ensure code name of custom table should be unique means don't try to use exact same name because it'll cause exception due to same table name already exist in DB. You can please share exception you getting while creating custom table so that I can help you out further.
I have an application that uses EF 5.0. Suppose That I have two tables:
tableA(IDTableA, IDTableB...)
TableB(IDTableB, ...)
When I query for elements of the tableA, I can do:
List<TableA> lstResult = myContext.TableA.SQLQuery("select * from TableA").ToList();
However, in this case the collection TableA.TableA in an entity of type TableA is not populate, is null, so I need to do other query:
1.- Convert all the IDs of my entity in lstResult to string in format ID1, ID2... I name this string strIDs.
2.- I do the query:
lst<TableB) lstResult2 = myContext.tableB.SQLQuery("select * from TableB where IDTableB IN(" + strIDs + ")").ToList();
In this moment, EF populates the colletion IDTableB in the tableA.
So this makes me do two queries. One to get the register of TableA and other to get the registers of TableB and know the relation between them.
If tableA has many FKs, then I need many additional queries, so I think that this is inefficient.
Lazy loading eorks in a similar way, do this additional queries when I need the information. However, I don't want to use lazy loading, because my dataContext has a short live, so when I return the entities as result of the query, when I try to get the childs records I get an error that says that the entity out of the context.
So other solution is to use a view, but I would like to know if it is posible to populate the child.
Also, I would like to use raw sql, because for dynamic queries for me is easier to create the query.
Thanks.
I have a entity framework database first set up and I'm having issues getting data from a table EF treats as an association because it's basically a navigation property. I have a Survey table with an EventId(PK), FacilityId, ExitDate, and Status. I also have a SurveyCategories table with CategoryID(PK), Description and a SurvCat table that just has SurveyId and CategoryId as foreign keys. I can get data from other related tables that don't use a middle table like SurvCat, but even following the documentation from the breeze site for navigation properties I cannot get anything loaded into the SurveyCategories array in each Survey object. I checked the metadata and it's showing the navigation property but I get nothing with this code:
var query = EntityQuery.from('Surveys')
.where("facilityId", "eq", whereClause)
.skip(currentPage * 5).take(5)
.expand("Facility")
.expand("SurveyCategories")
.expand("SurveyCite")
.expand("SurveyDL")
.orderBy(orderBy.survey)
.inlineCount(true);
Any help or links would be greatly appreciated.
I think that the answer for this other question can help you tu solve the problem: Error Loading related entities on demand (entityAspect.loadNavigationProperty()).
The N to N relations are not supported in breeze, so you have to use a intermediate entity to do work this.
I have an ios 5 app which does not create any data - it simply makes a GET call to a REST webservice and populates the sqlite database with those records. The initial GET works great when there are no records in the local database. However when I make subsequent calls, I will only be returning a subset of records whose data has changed since the last GET. But what is happening is that the records are just being added again, not updating the existing records.
I have an ID field which is the primary key (or should be) and when a record comes in whose ID already exists, I want that data to be updated. If that ID does not exist, it should be an insert.
I didn't see a way to set my ID field as a 'primary key' in the datamodel in XCode. I tried doing this in my didFinishLaunchingWIthOptions method:
userMapping.primaryKeyAttribute = #"id";
But that alone didn't really seem to do anything.
This is my call to actually perform the GET:
// Load the object model via RestKit
[objectManager loadObjectsAtResourcePath:[#"/synchContacts" appendQueryParams:params] delegate:self];
Which seems to do everything automagically. I am lost at this point as to where I should be putting logic to check to see if the ID exists, and if so do an update vs an insert, or what.
As of the latest RESTKit version (0.23) you can define the primary key like this:
[_mapping addAttributeMappingsFromDictionary:#{ #"id" : #"objectId", #"name" : #"name" }];
[_mapping setIdentificationAttributes:#[ #"objectId" ]];
Whereas objectId is you primary key on the core data object.
You seem to be doing it correctly and when your didLoadObjects callback happens you should be able to query Core Data for the objects you need.
You might be having an issue with the way your fetch requests are being set up. With the latest RestKit you can use RKObjectMappingProvider's
- (void)setObjectMapping:(RKObjectMappingDefinition *)objectMapping forResourcePathPattern:(NSString *)resourcePathPattern withFetchRequestBlock:(RKObjectMappingProviderFetchRequestBlock)fetchRequestBlock;
function and have the fetchRequestBlock fetch the proper data.
RestKit doesn't really handle partial update requests very well out of the box though. You might have more luck on the RestKit google group which is very active.
Quote:
I didn't see a way to set my ID field as a 'primary key' in the datamodel in XCode. I tried doing this in my didFinishLaunchingWIthOptions method:
userMapping.primaryKeyAttribute = #"id";
Keep in mind, the 'primaryKeyAttribute' is the one from your api payload, NOT a CoreData id, which CoreData manages on its own. RestKIt then maps the (invisible) CoreData primary key to the specified JSON key.