Swift5 and CoreData: Sorting fetchRequest by related Entity-Attributes - core-data

Even if I run the risk of asking a question twice and I'm too blind to see:
How can I sort a FetchRequest by an Attribute of an related Entity. In my special case, I've got three tables:
Client <-> ClientToContacts <-> Contacts. In a List View I like to list all ClientToContacs sorted by Contacs.lastName.
How can I do it by sortDescriptors?
This is my FetchRequest so far. But the sortDescriptors throw errors.
sortDescriptors: [
NSSortDescriptor(keyPath: \ClientsToContacts?.toContacts!.lastName, ascending: true),
NSSortDescriptor(keyPath: \ClientsToContacts?.toContacts!.firstName, ascending: true)
],
predicate: NSPredicate(format: "(toContacts.lastName CONTAINS[cd] %#) OR (toContacts.firstName CONTAINS[cd] %#) OR (toContacts.company CONTAINS[cd] %#) OR (toContacts.department CONTAINS[cd] %#) OR (toContacts.zip CONTAINS[cd] %#)", filter, filter, filter, filter, filter),
animation: .default
The predicate works fine so far and filters my results. Only sorting...
Thanks for helping. :-)

Related

Dynamically changing fetch request

I have the below fetch request which I want to be able to dynamically change the setup of.
The request is setup initially as
#SectionedFetchRequest(
sectionIdentifier: \.level,
sortDescriptors: [NSSortDescriptor(keyPath: \Card.level, ascending: true),
NSSortDescriptor(keyPath: \Card.setID, ascending: true),
NSSortDescriptor(keyPath: \Card.cardID, ascending: true),
NSSortDescriptor(keyPath: \Card.name, ascending: true)],
animation: .default)
private var cards: SectionedFetchResults<Int16, Card>
I've got the predicate change working fine, and worked out the sort descriptors now, but can't work out how to change the section identifier, when I try I get the error
Cannot assign value of type 'SectionedFetchResults<String, Card>.Type' to type 'KeyPath<Card, Int16>'
I'm trying to change it using
cards.sectionIdentifier = SectionedFetchResults<String, Card>

How to add 2 conditions in 'new nlobjSearchFilter'?

My code is like that:
var filters = new Array();
filters[0] = new nlobjSearchFilter("isperson", "customer", "is", "F")
filters[1] = new nlobjSearchFilter([["minimumquantity", "equalto", "0"], "OR", ["minimumquantity", "isempty", ""]]);
if (customerId) filters.push(new nlobjSearchFilter("customer", null, "anyof", customerId));
if (currency) filters.push(new nlobjSearchFilter("currency", null, "anyof", currency));
My question is how do I make filters[1] works with the 'OR' operator?
You were on the right track with the 'or' condition.
I can't tell which record you're trying to query, but the easiest way to control multiple and/or conditions when building a search is to use search "filter expressions" rather than manually building with nlobjSearchFilter().
If you want to continue using nlobjSearchFilter(), look up how to use the .setLeftParens()/.setRightParens() and .setOr() functions (example). They're not documented in the NetSuite help).
var filters = [
// this is how joins are referenced in filter expressions
// this is equivalent to nlobjSearchFilter('isperson', 'customer', 'is', 'F')
['customer.isperson', 'is', 'F'],
'and', [
['minimumquantity', 'equalto', 0], 'or', ['minimumquantity', 'isempty', null]
],
];
if (customerId) filters.push('and', ['customer', 'anyof', customerId]);
if (currencyId) filters.push('and', ['currency', 'anyof', currency]);

How apply where only a column is not null in adonis query builder

I need to check if the column percentage_correct >= parCorrect if percentage_correct <> NULL
I try something like:
const unidadeSequenceAtualEstudante = await Database.select("*")
.from("student_quiz_historics")
.where("student_id", idEstudante)
.where(function(){
this
.whereNotNull("percentage_correct")
.where("percentage_correct", ">=", parQtdAcerto)
})
.where("class_id", idClasse)
.where("book_id", idLivro)
.where("execution_back_status", "<>", "Cancelado")
.orderBy("sequence", "desc")
.first();
But when i have only records with the percentage_correct null, they still are trying to apply this where.
I'm having a little trouble replicating your problem. What you have there should work, but it's possible you're not considering something about SQL's behaviour with regard to NULL: anything compared to NULL is NULL, which is why the IS NOT NULL syntax exists. So for example:
foo=# SELECT 1 >= NULL;
?column?
----------
NULL
(1 row)
foo=# SELECT NULL >= 1;
?column?
----------
NULL
(1 row)
This means that you can kind of get away with not checking for the null at all, because only rows that meet the condition will be returned:
const unidadeSequenceAtualEstudante = await Database.select("*")
.from("student_quiz_historics")
.where({
book_id: idLivro,
class_id: idClasse,
student_id: idEstudante
})
.where('percentage_correct', '>=', parQtdAcerto)
.where("execution_back_status", "<>", "Cancelado")
.orderBy("sequence", "desc")
.first();
Is this a good idea? Debatable. I think it's probably fine for this purpose, but we shouldn't assume that NULL is the same thing as FALSE, because it isn't.
If you're still having trouble with your query, you'd need to provide more details about which database you're using, what your schema is and what kind of errors your getting.

Core Data #FetchRequest SwiftUI

I am trying to use a fetch request in a SwiftUI Charts package/CocoaPod. My issue is that when I use a ForEach to iterate over the Attribute (ACFTScores.totalScore) it populates one value per chart... I know this is because the BarChart is in the body of the ForEach but I don't know how to grab the range of the fetch and make it work with the SwiftUI Charts.
struct DashboardACFT: View {
#FetchRequest(entity: ACFTScores.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ACFTScores.totalScore, ascending: true)]) var acftScores: FetchedResults<ACFTScores>
var body: some View {
VStack {
ForEach(acftScores, id: \.id) { score in
BarChartView(data: [Int(score.totalScore)], title: "Title", legend: "Legendary")
}
}
}
}
I haven't worked with charts but you need to map your fetch request into an array containing the values you want to use in your chart. Something like this
var body: some View {
VStack {
BarChartView(data: acftScores.map {$0.totalScore}, title: "Title", legend: "Legendary")
}
}
}
Since you for some reason seems to need to convert the property to Int using compactMap might be better.
acftScores.compactMap {Int($0.totalScore)}

Filtering in ArrayList in C#

I have an ArrayList
ArrayList mixed = new ArrayList { "Joe", 200, "Root", false, "David" };
What is business logic should I use to filter only string from given ArrayList?
I mean I need {"Joe","Root","David"} as a filtered result.
I am using C# 4.0
You could use
var StringOnly = mixed.OfType<string>();
to filter your arraylist.

Resources