How can I get the number of entries under each job. Let's take a jobeet tutorial, here I want to show number of resume submits for each job.
Tables
job : id title
submit : id job_id file
Result :
title submits
job a 5
old job 20
I am using Doctrine. So, How can I do this ?
Something like that:
$job = Doctrine_Core::getTable('Job')->find(1);
// it will query the database to fetch the relation
$submit = $job->getSubmit()->count();
But if you want something more specific, show us your schema.yml.
If you want to avoid un new query to the database, you can fetch the relation with a leftJoin:
$job = Doctrine_Core::getTable('Job')
->leftJoin('Job.Submit')
->find(1);
// the relation is already fetched, so it won't perform a new query
$submit = $job->getSubmit()->count();
By the way, be careful with the ->count() method, if you have a lot of submits, this query won't be really optimized. The best, is to perform a manual query count:
$submit = Doctrine_Core::getTable('Submit')
->createQuery('s')
->select('COUNT(s.id) as total')
->where('s.job_id = ?', array($job->getId()))
// HYDRATE_NONE won't hydrate the return object
->execute(array(), Doctrine_Core::HYDRATE_NONE);
// I guess the value is here but test yourself
var_dump($submit[0]);
Related
So I am working on this existing rails application where I am accessing 2 tables from 2 different databases.
scope :comp_ids_in, lambda {|comp_ids| where(:comp_id => comp_ids)}
company_info = CompanyInfo.comp_ids_in(my_array_of_ids)
the above company_info returns back an an array of ActiveRecord:Relation CompanyInfo objects.
Now I want to compare the above company_info objects with another table on a different database
and return back all the found results in an object.
My existing attempt in my controller would return back only 1 result at a time.
company_info.each do |info|
# RemoteInfo is an acive record class which accesses record from a different database
remote_info = RemoteInfo.where(username: current_user.username, property_code: info.org_id, chain_code: info.site_id)
end
I want all the results stored in the remote_info object. So that I can loop through that object and get any information that was returned.
I would appreciate it if some one can suggest me an efficient approach.
If you are not worried about the order, it would be efficient to just make one query to get all the remote info
remote_info = RemoteInfo.where(username: current_user.username, property_code: company_info.collect(&:org_id), chain_code: company_info.collect(&:site_id))
I am working on an iOS app, running on Parse(backend).
I am having problems with accessing the contents of another class from a query I made.
So I have this table. Let's call it "Contests". it has the following data:
name,
date start,
date end,
pointer to organization table (the objectid)
And then the organization table:
name,
number of Facebook likes,
I want to be able to access the name of the organization and every other detail a certain contest has. Will I have to put a query inside another query, slight problem with that is that the queries require waiting time and it accomplishes it in the background. So I have:
findInBackground() {
findInBackground() {
}
}
Is there any better way to do this? Also I am getting multiple objects at the same time.
You need to do a query on your Contest table with whatever requirements you have but then add an includeKey call:
var query = PFQuery(className:"Contests")
//...Other query requirements
query.includeKey("organization")
query.findObjectsInBackgroundWithBlock {
}
includeKey will force fetch of the organization along with the contest details in 1 query.
There are three tables:
users
schedules
schedules_users
The user-model and the schedules-model each have the has_and_belongs_to_many-relationship.
Now I simply want to do this:
user_id_binded = Schedule/User/Object/#I dont know!#.find_by_sql ["SELECT schedules_users.user_id FROM schedules_users WHERE schedules_users.schedule_id = ?", schedule.id]
#user_schedules_binded = User.find(user_id_binded)
BUT the return-value of the first find_by_sql must be a model, as I understood the Rails.Api correctly.
It's neither a user-model-return-value or a schedule-model-return-value.
In the schedules_users-table are all relationships between users and schedules.
So I want to get all users which are binded to a specific schedule.
First I thought this should be the right way to solve it, but at that moment I didn't know that the return-value must be a model.
How could I solve this problem?
It appears you have a schedule ID and want the users in the end - that can be done easier by join statement like #user_schedules_binded = User.joins(:schedules).where(schedules: { id: schedule_id })
Or, if you have the schedule object, schedule.users will do the same, both going through schedules_users table.
I have a list of events like so:
events = Events.all
Events have a many-to-many relationship with Users via class UserEvents modeled after the approach from spring-security-plugin:
I would like to find out whether a User is attending an Event and I can do that by running this:
UserEvent.get(currentUserId, eventId)
Question
How can I do this over all the elements of my list events so that in my view layer I can easily find out whether currentUserId is going to the event?
You can query for all of the associated Users for an Event like this:
def user = ...
def events = UserEvent.findAllByUser(user).event
This is a fairly efficient query since it executes SQL similar to
select * from user_event where user_id=?
and then loads each Event. This is N+1 though since it loads each Event individually, so you can do it more efficiently with this:
def eventIds = UserEvent.findAllByUser(user).eventId
def events = Event.getAll(eventIds)
The first line just gets the event ids using the same SQL as above, then the second line runs SQL like
select * from event where id in (?, ?, ?, ...)
If you only need a subset of your events which the user attends, then go with what Burt Beckwith sugeested.
But, if you need the whole set of events and just add an attribute you should use metaClass.
event.metaClass.userAttends= ...
you can see explanations about metaClass here
Specifically in your situation i would get all ids as Burt Beckwith said and the check for each event if its id is in the list:
def eventIds = UserEvent.findAllByUser(user).eventId
expandedEvents = events.collect {event->
event.metaClass.usetAttends = eventIds.contains(event.id)
return event}
You could use grep() to filter the list of events by whether UserEvent.get() returns an item.
events.grep { UserEvent.get(currentUserId, it.id) }
I have coded three select statements in stored procedure in Microsoft SQL Server 2005. Both select statements return multiple number of records and table list for select statements is different. One select records from a master table and the other from a child table. In C# code I want to get all these records and put all the data in one object. I am using SqlDataReader. Is it possible with it or should i do something else.
You use the NextResult method on the datareader to navigate with multiple results from a query.
To loop through all data you would do something like this:
var moreResults = true;
while (moreResults)
{
while (reader.Read())
{
...
}
moreResults = reader.NextResult();
}
So with that as a background, and assuming the master resultset comes first, populating master and detail objects could be done like this:
First, build up a dictionary of the Master records:
var masters = new Dictionary<int, Master>();
var idOrdinal = reader.GetOrdinal("id");
while (reader.Read())
{
var id = reader.GetInt32(idOrdinal);
masters.Add(id, new Master{Id=id, ....});
}
Next, move on to detail records and add those to their corresponding master:
reader.NextResult();
var masterIdOrdinal = reader.GetOrdinal("masterId");
while (reader.Read())
{
var masterId = reader.GetInt32(masterIdOrdinal);
var master = masters[masterId];
master.Details.Add(new Detail{....});
}
You should obviously replace column names with what you have in your data as well as supply the full initialization of Master and Detail objects.
If the detail resultset is sorted on master id, the last loop could be optimized to only lookup each master once from the dictionary. If the resultsets are small though, the gain would not be that huge.
...one select records from master table
and other from child table .in c# code
i want to get all this record and put
all this data in one object...
Peter's solution works to solve the basic problem of retrieving multiple results with a single DataReader. However, If you want to save your data to an object which replicates the relationship between the Master-Details tables, you should be using a DataSet instead.
DataSets can contain multiple DataTables and provide full support for inherent relationships between the tables by allowing creation of DataRelations between the tables. Then you can get related records for each scenario by calling GetChildRows() or GetParentRows() from the Master or Details tables respectively.
There are probably many samples online that illustrate how to do this. Here's one discussion thread from my Group where I have listed the steps and provided some code to demonstrate the procedure.