Grails; how to refer to a domain property in native sql query - sql

I have a domain class UserProfile which has one to one relationship with another domain class User.The Structure of the domain is provided.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
static constraints = {
// some constraints
}
static mapping = {
//some mapping; user property is not mapped
}
I need to write a native sql query in Grails for UserProfile domain and I don't know how to refer to user property(static belongsTo = [user: User]). I have tried USER_ID but it is not working.
I can't name the column directly using mapping section; I just need to find out how user column in UserProfile domain is named in database and how it can be called in native sql query.

Very Simple if i got your question ,Grails gorm convention for storing fileds in data base is:
Like
user_profile for UserProfile -Domain
and all fileds are speparedted by underscores and most of the time gorm adds _id after a foreign key reference /or a GORM relationship like above One to One and one to Many
[belongsTo=[user]] .
Inside SQL Table
mysql describe user_profile ;
----------------------------------------------------------------
User_Profile
----------------------------------------------------------------
id
version
foo varchar(50)
postion
email
user_instance_id int
-------------------------------------------------------------------
NATIVE SQL QUERY WILL BE :
'select up.user_instance_id from user_profile as up '
the Get all the userInstance objects by querying the user table
'select * from user where user.id = 'the id you get it from the above query'
I hope you have some idea on this please ,if i didnt get it let me know.

I believe if you define user inside UserProfile, then you can access it and will automatically be mapped? It works in my previous projects, I hope it will work with this.
сlass UserProfile {
String fio
String position
String phone
String email
static belongsTo = [user: User]
User userInstance;
static constraints = {
// some constraints
}
Then you can use it
UserProfile.executeQuery("select up.userInstance from UserProfile up")

Related

Ensuring Unique Email Address in Documents

I want to create or update a UserAccount entity with an EmailAddress property, whilst ensuring the EmailAddress is unique. UserAccount has it's own Id property of type long, this is just so I can track each UserAccount entity, as using the email address as the document id would present issues if the user wishes to change their email address.
I've heard I could create a new collection called UniqueEmailAddresses that could be collection of empty (or near empty?) documents and the email address would be the actual document id.
Is this correct? If I update both collections in one transaction, is this the best way to ensure that 2 documents with the same email addresses don't end up in UserAccount collection? Does adding this extra collection with the user's email address as the id, cause any performance issues when dealing with millions of users? Is it possible to create an empty document? Am I going down the right path?
EDIT
These are the available bundles, which bundle do I need to add to get the unique constraint features?
EDIT 2
I've added the Raven.Bundles.UniqueConstraints DLL to the folder ~/App_Data/RavenDB/Plugins (I'm using the embedded server) and changed my Document Store Provider to:
protected override IDocumentStore CreateInstance(IContext context)
{
EmbeddableDocumentStore documentStore = new EmbeddableDocumentStore()
{
DataDirectory = #"~\App_Data\RavenDB",
UseEmbeddedHttpServer = true,
Configuration = { Port = 8181, PluginsDirectory = #"~\App_Data\RavenDB\Plugins" }
};
documentStore.RegisterListener(new UniqueConstraintsStoreListener());
documentStore.Initialize();
return documentStore;
}
But it still doesn't show in the available bundles list and my call to checkResult.ConstraintsAreFree() wrongly returns true when I'm testing by breaking the constraint.
RavenDB has the notion of the unique constraints bundles that does all of it for you.
See the docs:
http://ravendb.net/docs/article-page/3.0/csharp/client-api/bundles/how-to-work-with-unique-constraints-bundle

GORM One-to-Many relationship without foreign keys

I've been trying for a while to understand how GORM works, and I think I've got it down. However, I'm having a heck of a time getting my relationships correct.
Here is my database schema setup (2 tables):
Table - Users
userhash varchar(255)
firstname varchar(255)
lastname varchar(255)
Table - Logs
userhash varchar(255)
accessdate date
There are no foreign key and primary key constraints defined in the tables. However, in the users table the userhash will be unique. I didn't design it this way, but I have to use it like this.
Now for my Grails domain classes:
Class - Users
class Users {
String userhash;
String firstname;
String lastname;
static hasMany = [logs: Logs]
}
Class - Logs
class Logs {
String userhash;
Date accessdate;
static belongsTo = Users;
}
In my controller, I do the following:
def user = Users.findByUserhash("nraboy");
println user.firstname;
println user.logs;
It prints out the correct firstname, but when I try to display the logs, it is null or empty. Am I requesting the data incorrectly for child tables or am I missing something somewhere in the domain class design?
I've tried to do the following, but had now luck as well:
Class - Logs
static mapping = {
id generator: "assigned", name: "userhash", type: "string"
}
Class - Users
static mapping = {
userhash generator: "foreign"
}
I figured the above would let me manually define the primary key and foreign key via code since it didn't exist int he tables. No luck though.
Any help would be appreciated.
Thanks,
It looks like you may have to do something with in Users for the logs association to force the foreign key to be in the Logs table, as it is. See the GORM docs One-to-Many Mapping section. Perhaps something like:
static hasMany = [logs: Logs]
static mapping = {
logs column: 'userhash'
}
I would be curious to hear if this worked...

use of mappedBy in Many to Many relationship in Grails

I am a newbie to Grails and am having a lots of problems in a many to many relationship especially when the mappedBy comes into picture. Here is the exact problem that I am facing.
I have two domain classes which have a many to many relationship.
class Address {
Long id
String addName
static hasMany = [policy: Policy]
static belongsTo=[Policy]
Date lastUpdated
Date dateCreated
}
and
class Policy {
int id
int policyId
Date lastUpdated
Date dateCreated
static hasMany = [addressSource:Address,addressDestination: AddressSet]
}
Now this creates 4 tables, namely : address, policy, policy_src_add and policy_dest_add
The problem that I am facing is with the 'show' view (The views are the standard ones generated by Grails by the generate-views command).
In the show view of Address I can see the Policies that are referenced by policy_dest_add but not the ones that are referenced by policy_src_add.
For ex : Let us assume there is a policy:"PK" which has addressSource:"AS"(lets say id=1) and a addressDestination :"AD"(lets say : id=2)
When i go to the show view of "AD" (which is /address/show/2 ) I can see the Policy "PK" but when i go to the show view of "AS" (which is /address/show/1 ) I can NOT see the Policy "PK" in it.
Can someone please help me.Is this a view generation problem in case of many to many relationships in grails? Or is it just something I am missing ?I have tried using mappedBy in the Address as follows but to no avail :
static mappedBy = [policy:"addressSource", policy:"addressDestination"]
Thanks a ton,
Manas Shukla

typo3 extbase permissions in extensions

I have written one extension for making service order.
The issue I am facing here is,
There are FE users belong to three FE user groups namely "client", "Admin" and "Employee".
Here the client can make order and he should be able to see only his orders.
And the admin can see all orders done by different clients.
And the employee should be able to see only some clients orders.
Currently I made a order table with N:1 relation with FE user table. So every order should relate with any one client.
So in controller, I am checking the login user and using custom query in repository, I am accessing order related to loggedin client (FE user)
In file OrdersController.php
public function listAction() {
$orders = $this->ordersRepository->orderForLoginUsr();
$this->view->assign('orders', $orders);
}
In file OrdersRepository.php
public function orderForLoginUsr(){
$loggedInUserId = $GLOBALS ['TSFE']->fe_user->user['uid'];
$query = $this->createQuery();
$query->matching(
$query->equals('user', $loggedInUserId)
);
$query->setOrderings(array('crdate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING));
return $query->execute();
}
But here my question is how to make admin user able to see all the orders done by all clients?
I have to write different template and action that calling function findAll() ?
$orders = $this->ordersRepository->findAll();
And how to set for usergroup Employee ?
Thanks in Advance
I think that the easiest way is to actually implement 3 actions with 3 different plugins, something like: listClientAction, listAdminAction and listEmployeeAction
In each of those action, you implement a method in your repository that fetch the right list of order with the good ordering:
orderForLoginClient(), orderForLoginEmployee(), orderForLoginAdmin()
What does the trick actually is that there will be 3 plugins on your page, one for each action. In each instance of your plugin, you set the access for the right be_group.
Don't forget to add the actions and plugin in the localconf and ext_table files.
I hope it will help!
Olivier
If your view is almost the same for client, admin, employee you should simply add a method like getOrderWithPermissionsForUser($currentUser);
In the method itself you should check for the usergroup and call different queries on your Repo.
If your view is different from usergroup to usergroup, you should use different templates with partials for the same parts.
If the data of the views is the same, just change the template for each usergroup in the action. If not use different actions.
Here is a helper method for easily changing your templatefile.
/**
* This method can change the used template file in an action method.
*
* #param string $templateName Something like "List" or "Foldername/Actionname".
* #param string $templateExtension Default is "html", but for other output types this may be changed as well.
* #param string $controllerName Optionally uses another subfolder of the Templates/ directory
* By default, the current controller name is used. Example value: "JobOffer"
* #param \TYPO3\CMS\Fluid\View\AbstractTemplateView $viewObject The view to set this template to. Default is $this->view
*/
protected function changeTemplateFile($templateName, $templateExtension = 'html', $controllerName = null, AbstractTemplateView $viewObject = null)
{
if (is_null($viewObject)) {
$viewObject = $this->view;
}
if (is_null($controllerName)) {
$controllerName = $this->getControllerContext()->getRequest()->getControllerName();
}
$templatePathAndFilename = $this->getTemplateRootpathForView($controllerName . '/' . $templateName . '.' . $templateExtension);
$viewObject->setTemplatePathAndFilename($templatePathAndFilename);
}

MVC4 Postal - Accessing User Email Address searching by UserId

I have a site where user A can book a lesson with a teacher, I then want to have an email sent to the teachers saying user A wants to book a lesson with you etc.
I have postal up and running sending emails without issue,
however, I don't know how to access the email address of the teacher to send the email.
The email address is saved as part of the built in UserProfile table. I have the teacher's UserId (as it's stored in a separate teacher table).
So is there a way to access the teachers email ,searching by UserId?
In any other table I would use t in db.Teacher.find(id) but this doesn't work within the Account Controller.
This was built using the default MVC4 internet website template using the built in simple membership. Let me know if more information is needed.
I've added the following to the AccountController;
private UsersContext db = new UsersContext();
public ActionResult EmailNotification(int id)
{
var user = from l in db.UserProfiles.Find(id)
select l;
}
db.UserProfiles.Find(id) however gives the following error;
Could not find an implementation of the query pattern for source type 'LessonUp.Models.UserProfile'. 'Select' not found.
Which I assume is a result of it not being created through the entity framework?
I think your query needs to be something like the following:
var result = from q in context.UserProfiles
where q.UserId == id
select q;