I have the following piece of code in ItemController.groovy
def list = {
params.max = 60
def storeYYId = params.id
[itemInstanceList: Item.list(params), itemInstanceTotal: Item.count()]
}
I have the following in Item.groovy:
class Item {
String itemName
static belongsTo = [store:Store]
static constraints = {
itemName(blank:false)
storeId()
}
}
This gives me an error since it tells me that there is no storeId property, but there is, since store_id is a foreign key to the Store table in the corresponding database.
Question1. How do I tell grails to let me access the properties of domains that are autogenerated by GORM, like the id and storeId in this case?
Question2. What code should I write in my ItemController.groovy in my list action, in order to retrieve only a list of items where the storeId == storeYYId ?
Question1. How do I tell grails to let me access the properties of
domains that are autogenerated by GORM, like the id and storeId in
this case?
You should be able to access autogenerated properties in exactly the same way as you access properties that you define. The reason you're getting an error is because Grails does not automatically generate a storeId property for the Item class, the only properties it will autogenerate are version and id (for both Item and Store).
Question2. What code should I write in my ItemController.groovy in my
list action, in order to retrieve only a list of items where the
storeId == storeYYId ?
You'll need to write either a HQL or criteria query to retrieve these items. The criteria query would look something like this (untested)
// Get all items that have storeId = 6
def storeId = 6
def items = Item.withCriteria {
store {
eq('id', storeId)
}
}
Related
My Model Classes (shortened):
class Customer: RealmSwift.Object {
let orders = List<Order>()
}
class Order: RealmSwift.Object {
#objc dynamic var areaCode: String? = nil
#objc dynamic var isPaid: Bool = false
}
Now I want to get all Customers with non paid orders in a given area.
I use this query to get them (I tested this query using Realm Studio):
orders.areaCode == '5429' and orders.isPaid == false
But with this Query I don't get only customers with non paid orders in '5429'.
I also get customers with orders in '5429' and paid orders in another area.
But I get only customers with both parts, but even in different rows.
How can I change my query to get only "customers with non paid orders in '5429'"?
You can use a subquery to find all Customers whose orders property contains at least one Order, where the areaCode is "5429" and isPaid is false.
let areaCode = "5429"
let nonPaidInArea = realm.objects(Customer.self).filter("SUBQUERY(orders, $order, $order.areaCode == %# AND $order.isPaid == false).#count>0",areaCode)
I have written a domain class
class ReportCallByUser {
Integer userId;
String userName;
String reportName;
Date timeOfReportCall;
static constraints = {
}
static mapping = {
timeOfReportCall index: 'time_of_report_call_index'
}
The last line creates an index in database but in ascending order. How can I create index on 'timeOfReportCall' with descending order?
Thanks in advance.
There's no such thing as order in regards to index creation. It's the query's ability to specify the ordering:
ReportCallByUser.list( [ sort:'timeOfReportCall', order:'[desc|asc]' ] )
I am assuming that you want the results in descending order by default when you query the database using GORM. If that is the case, you can specify sort order in your mapping as such.
static mapping = {
sort timeOfReportCall:"desc"
}
Hope that helps.
My domain class is
class RoomWantedAd{
Set<MateAgeRange> mateAgeRanges
static hasMany=[mateAgeRanges :MateAgeRange]
}
Her MateAgeRange is :
enum MateAgeRange {
TWENTIES('18-29')
,THIRTIES('30-39')
,FOURTIES("40-49")
,FIFTIES("50-59")
,SIXTIES("60+")
final String value
private MateAgeRange(String value) {
this.value = value
}
String toString() { value }
String getKey() { name() }
static belongsTo=[roomWanted:RoomWanted]
}
My problem is searching. In the search page, a person can select 0 or more values in [18-29, 30-39, 40-49, 50-59, 60+]. In the db, 0 or more values among [18-29, 30-39, 40-49, 50-59, 60+] are stored in field 'mateAgeRanges'.
Let db contains [30-39, 50-59] in 'mateAgeRange' field. Let in the search page, the user selects [18-29, 50-59, 60+]. Then the Ad corresponding to the above list must be returned. This is because at least one value in user's selection is present in the db list. How is it possible. Is it possible using an SQL query or grails GORM query.
you have to use exactly the same <g:select/> tag as you are using for create/update. Thus, you will see human readable values like THIRTIES in browser, but in the background the '30-39' values will be used.
Using MVC 4 with EF code First.
When doing linq to EF selects statements, the collections are being populated with what seems like the last record's data. And what's weirder, only some of the properties are repeated where others are not. It is best to show you by example:
Using this query returns the proper data:
var orders = db.Orders.ToList();
OrderID OrderTotal Name
1 215.00 Bob
2 415.00 Mark
3 315.50 Ralph
When I filter the Orders entity by a SubscriberID, which is a foreign key, like so:
var orders = db.Orders.Where(s => s.SubscriberId == 2).ToList();
The data end up looking like this:
1 315.50 Bob
2 315.50 Mark
3 315.50 Ralph
Notice how the OrderTotal is repeated but the names stay the same. Please note that this is not a view issue. When I look at the data in the collection while debugging in the controller, this is what I see. This does not appear to be the only place this is happening. I am seeing something similar with more complicated models - but I thought I'd start with the simplest sample. Thanks!
The problem was caused when I was setting default values on my models. Apparently using static was incorrect. So:
[ReadOnly(true)]
[Display(Name = "Sub total")]
private static decimal _OrderSubTotal = 0;
public decimal OrderSubTotal { get { return _OrderSubTotal; } set { _OrderSubTotal = value; } }
Should be written as
[ReadOnly(true)]
[Display(Name = "Sub total")]
private decimal _OrderSubTotal = 0;
public decimal OrderSubTotal { get { return _OrderSubTotal; } set { _OrderSubTotal = value; } }
I am running a grails application and I am receiving the weirdest error I've probably ever encountered. One "field" in a model got data that just disappears for no reason.
I have two Model or a Domain class in my project with the following set up:
class Insertion {
String title
Date insertDate
static hasMany = Dataholder
static constraints = {
title(unique: true)
}
}
class Dataholder {
String product
int somenumber
int somenumber2
int somenumber3
Date startDate
Date endDate
List<String> somedatalist
Insertion insertions
static belongsTo = Insertion
static constraints = {
}
}
The "insertion" class is representing every time a user might input a bunch of dataholders. The dataholder represents all the data for that specific product. Important to know is that the data that disappears is contained in the Dataholder model and the ONLY data that disappears is the somedatalist.
This is the magic which is completely confusing, when I insert the data and saves it. It all goes well:
if (!errors) {
dataholderValidator.each {
it.insertion = insertion
it.save()
}
def results = Dataholder.findAllByInsertion(insertion)
I do some validating and apply data to every Dataholder and then if everything goes well, if(!errors) I add the insertion to each object. After that is done I save each objec, saving the data to the database. You may think it's going wrong here but just wait and be amazed.
After saving I get all the Dataholders from the database (since I want to be sure that the data was saved before printing it out to the user) by using the insertion. This is where the strange part begin, what I get back is the correct data:
results.each {
it.somedatalist.each { it2 ->
if(!weekdays.contains(it2))
weekdays.add(it2)
}
}
Populate an array with all the unique items from the datalist. Then printing it out to the view and voila:
Now, we just wait for the users confirm of all the data in the view and when he or she is clicking on a confirm button the insertion title is sent with post to function which would retrieve the data and to my surprise the somedatalist is null.
This is the functionality that retrieves the data:
def result = Insertion.findByTitle(insertionTitle)
def results = Dataholder.findAllByInsertions(result)
When putting a breaking point after results I can for sure confirm that every Dataholder contains the correct the right data except that somedatalist which is equal to null.
I've tried to get the data above by using the Insertion Title instead of just using the object and it works well. I can't understand why the data is populated in the database in one second and how something can just disappear?
Test:
void testSaveDataholder() {
Insertions insertion = new Insertion(title: 'adadad', insertDate: new Date())
insertion.save()
assert Insertion.all.size() == 1
Dataholder ed = new Dataholder(product: 'abc123', somenumber: 123, somenumber2: 13, startDate: new Date(), endDate: new Date(), somedatalist: ['TI'], insertions: insertion)
ed.save()
assert Dataholder.all.size() == 1
assert Dataholder.all.first().somedatalist.size() == 1
assert Dataholder.all.first().insertions.title == 'adadad'
assert Insertion.findAllByTitle('adadad').size() == 1
assert Dataholder.findAllByInsertions(Insertion.all.first()).size() == 1
}
This test all returns true, I am using Grails 2.1.
EDIT: I am using the in-memory database with "update" as configuration. So I can't really view the data. But it should be there.
Please help me with your sage advice and better wisdom.
It just has come to my mind. Persisting a collection of objects into single column breaks the 1st normal form, so it is not the correct way to do it. I have immediately googled an issue in JIRA:
http://jira.grails.org/browse/GRAILS-1023
The correct way is to create a new domain class with single String attibute and use standard one-to-many relation.