Showing posts with label hasmany. Show all posts
Showing posts with label hasmany. Show all posts

Monday, August 28, 2023

Grails / GORM apply criteria query with hasmany String for filter

I have a domain object (User) like this:
class User {
   String name

   static hasMany = [
      permissions: String
   ]
}
And I am trying to query all the User with certain permissions. So I have to join and check permissions property. Here how we can do this -
User.withCriteria {
    createAlias('permissions', 'n') 
    ilike 'n.elements', '%permission_1%'
}
The trick is to use 'n.elements'

Tuesday, January 22, 2013

A find condition about hasMany(has many) relationship in cakephp

Suppose you have two model User and UserRole.
And User has many UserRole.
Now you want to find User By specific UserRole.

User:
Fields: id, name, others........
var $hasMany = array(
    "UserRole"
);

UserRole:
Fields: id, user_id, role_id, others...var 
$belongsTo = array("User");

First you need to find all UserRole by your own conditions:

$userRoles = $this->UserRole->find("all", array(
    "conditions" => array(
        "UserRole.condition" => $value
    )
));

Now find User by UserRole as follows:

$users = $this->User->find("all", array(
    "conditions" => array(
        "User.id" => Set::extract("/UserRole/user_id", $userRoles)
    )
));


BINGO...