Count second level set of model in nhibernate - nhibernate

I want to count set of set of model in NHibernate using Criteria Query.
Account Model have Contacts(set) and Contact Model have Addresses(set).
I want to count addresses by giving input Account object.
I have implemented temporary by simple foreach loop.
If anyone know then please help me.
Thanks in advanced.

Thanks Radim Köhler,
I found my solution by :
var count = (Int32)Session.CreateCriteria(typeof(Account))
.Add(Restrictions.Eq("Id", account.Id))
.CreateCriteria("Contacts", "Contacts", JoinType.InnerJoin, Restrictions.IsNotEmpty("Addresses"))
.SetProjection(Projections.Count("Id")).UniqueResult(); .
Then I have used following criteria query:
var count = (Int32)Session.CreateCriteria(typeof(Address))
.CreateCriteria("Contact", "Contact",JoinType.InnerJoin)
.Add(Restrictions.Eq("Account.Id",accountId))
.SetProjection(Projections.Count("Id")).UniqueResult();
This give me actual result that I want by optimal query.

Related

Querybuilder with array of Id's in a one to many situation

I'm using Symfony 3.4 and its doctrine querybuilder. I have an entity Ad that has different options in a one too many relation. Therefore I'm building a filter.
$optionIds is a array with multiple integers representing the option.id
I have the following filter:
$query->leftJoin('ad.options', 'opt')
->andWhere($query->expr()->in('opt.id', ':optionIds'))
->setParameter('optionIds', $optionIds)
Problem with this filter is dat it returns all ads that have one of the options linked. The idee is to get only the ads that have all id's linked. So this filter is a OR instead-off an AND filter?
Second issue is that it return multiple time the same ad if it matches multiple options ids. I don't want to use groupBy to solve this agina.
I also change the code to the following:
$cnt = 0;
foreach ($optionIds as $optionId) {
$query->leftJoin('ad.options', 'opt'.$cnt)
->andWhere('opt'.$cnt.'.id = :id'.$cnt)
->setParameter('id'.$cnt++, $optionId);
}
This works but is very slow.
Help is appreciated, i'm stuk already half a day!
To check if all options should exist for the ad you will need to use aggregation and filter on aggregated result
$query->addSelect('COUNT(DISTINCT opt.id) AS total_options')(
->leftJoin('ad.options', 'opt')
->andWhere($query->expr()->in('opt.id', ':optionIds'))
->addGroupBy('ad.id')
->having('total_options = '.count($optionIds))
->setParameter('optionIds', $optionIds)
For reference and more details see my other answers for similar situation in a many to many relation
Symfony2 - Doctrine2 QueryBuilder WHERE IN ManyToMany field
Sql/Doctrine query to find data with multiple condition with Many to Many associations

Sorting out data from SQL in Rails

So I'm trying to get some specific data out of my database but I've searching online and can't find how to do this (probably because I'm searching for the wrong terms).
I start with getting all the participants with a specific id like this :
contributions = Participant.where(user_id: params[:id])
This will give me a json result like this :
0: {id_request: "1", user_id: "titivermeesch#gmail.com"}
1: {id_request: "2", user_id: "titivermeesch#gmail.com"}
So here I have all the requests (there is a Request class) that have that specific user_id.
Now I want to do this :
all = Request.where(id: id_request)
This obviously don't work but how would I get all those requests that have all those id's that come from the first database query?
So with the results above I should get Request 1 and 2, but how? Can anyone guide me?
How about
contributions = Participant.where(user_id: params[:id])
# Assuming the above is an active record query and id_request is a property of Participant
all = Request.where(id: contributions.map(&:id_request))
This is the equivalent of the SQL
select * from requests where id in (array_of_request_ids)
If You added associations in your model? it's very easy to retrieve the records
This should work:
Request.joins(:participants).where("participants.user_id = ?", params[:id])
Also you might want to read the following part (on joins)

Filter records based on groups [Odoo]

I am trying to filter the records based on their group id. I have written a domain filter in menu action like this
[('pending_approver','in',[g.id for g in user.groups_id])]
pending_approver is a Many2one field with res.groups
Have a look on this for more clarification.
def _default_approver(self):
obj = self.env['approval_heirarchy.approval_rules'].search([('id', '=', 1)], limit=1)
if obj.x_approver_ids:
val = obj.x_approver_ids[0].x_user_ids
return obj.x_approver_ids[0].x_user_ids.id
pending_approver = fields.Many2one('res.groups', string="Pending Approver", readonly=True,default=_default_approver)
Whenever run the application prompt an Odoo Client Error:
Uncaught Error: Expected "]", got "(name)"
I've searched a lot but didn't find any solution.
Any help will be a great regard for me. Thanks in Advance!
if self.user_has_groups('sales_team.group_sale_manager') is True:
code part...
this code may help you.....any queries please free to ask

Order by record count on sub collection

I am trying to convert some old code to use Fluent Nhibernate.
Old code:
allOrders.OrderBy(x => x.OrdersLineItems.Count);
How do I convert it to something like:
query.AddOrder(new Order(????, true));
Is this even possible?
Thanks in advance
UPDATE:
Here is the simplified code I am trying to write:
ICriteria query = FluentSessionManager.GetSession().CreateCriteria<Orders>()
.AddOrder(new Order(????, true));
The joined table is OrdersLineItems. I need to set the order by the count of the line items. Since I am using paging with a data set that has over 500,000 records, simply pulling all the records into memory and then sorting them will not.
Thanks in advance.
ICriteria query = FluentSessionManager.GetSession().CreateCriteria<Orders>()
.CreateAlias("this.OrderLineItems", "oli")
.AddOrder(new Order(Projections.Count("oli.Id"), true));
Something like that I should think. It's probably not perfect but at least illustrates that you need to use Projections.Count to get it done.

Does CDbcommand method queryAll() in yii return indexed entries only?

I am trying to retrieve data from a simple mySql table tbl_u_type which has just two columns, 'tid' and 'type'.
I want to use a direct SQL query instead of the Model logic. I used:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('type')->from('tbl_u_type')->queryAll();
return $userArray;
But in the dropdown list it automatically shows an index number along with the required entry. Is there any way I can avoid the index number?
To make an array of data usable in a dropdown, use the CHtml::listData() method. If I understand the question right, this should get you going. Something like this:
$command = Yii::app()->db->createCommand();
$userArray = $command->select('tid, type')->from('tbl_u_type')->queryAll();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($userArray,'tid','type'));
You can also do this with the Model if you have one set up for the tbl_u_type table:
$users = UType::model()->findall();
echo CHtml::dropdownlist('my_dropdown','',CHtml::listData($users ,'tid','type'));
I hope that gets you on the right track. I didn't test my code here, as usual, so watch out for that. ;) Good luck!