Laravel collection condition in sum - collections

I have a collection of transactions with relations and I would like to sum column separated by condition of relation column. Right now I have this:
$delegatedProvision = 0;
$ownProvision = 0;
foreach ($transactions as $transaction) {
if ($transaction->discount->consider_improvement) {
$delegatedProvision += $transaction->stats->$column;
continue;
}
$ownProvision += $transaction->stats->$column;
}
$this->salesCollection->put('delegatedProvision', $delegatedProvision);
$this->salesCollection->put('ownProvision', $ownProvision);
It works but I would like to use Laravel collections. So far I have just this:
$provision = $transactions->sum(function ($transaction) use ($column) {
return $transaction->stats->$column;
});
And I don't know how to use condition in sum() method and according column $transaction->discount->consider_improvement (which is boolean) have sum in separated variables. I can use filter each for different consider_improvement but it means that I have to iterate all transactions twice.

Try this:
$collection->where(/* your condition */)->sum($column);

Related

How to add new item in specific index?

I new in kotlin , i want to update an item in lists.
I use this code:
var index: Int
for (record in recordList)
if (record.id == updatedHeader?.id) {
index = recordList.indexOf(record)
recordList.add(index, updatedHeader)
}
but it cant do this, because of ConcurrentModificationException
Assuming that recordList is a MutableList and val (so, you'd like to modify the records in place), you can use forEachIndexed to find the records you care about and replace them.
This did not cause a ConcurrentModificationException:
recordList.forEachIndexed { index, record ->
if(record.id == updatedHeader?.id) recordList[index] = updatedHeader
}
On the other hand, if you redefine recordList as a non-mutable list, and a var, you could rewrite the entire list using map:
recordList = recordList.map { if(it.id == updatedHeader?.id) updatedHeader else it }
Of course, you could call .toMutableList() on the end of that if you wanted to turn your List into a MutableList.
If there's a single record with the given id in the list, you can find its index and add the header at that index:
val index = recordList.indexOfFirst { it.id == updatedHeader.id }
if (index >= 0)
recordList.add(index, updatedHeader)
If there are multiple records with the given id and you want to prepend header before each of them, you can use get listIterator and use its methods to modify the list during the iteration without getting ConcurrentModificationException:
val iterator = recordList.listIterator()
for (record in iterator) {
if (record.id == updatedHeader.id) {
iterator.previous() // move to the position before the record
iterator.add(updatedHeader) // prepend header
iterator.next() // move next, back to the record
}
}

How to read a specific item in a vector?

I have a viewScope "selection" which is a vector.
I would like to be able to read a specific elementh (third in this case)
I thought dooing it with an iterator like this , but it just gives me all the elements instead of the third...
var i = 0;
for (var it = viewScope.selection.iterator();it.hasNext();i++ ) {
if (i == 3){
sessionScope.example="item "+i+"="+it.next();
}
}
Maybe I don't really understand your question, but you can get the third element via index, i.e. like
viewScope.selection[2]
or
viewScope.selection.get(2)

xBestIndex malfunction (passing non-literal parameters to table valued function)

I'm trying to implement a table valued function (as a SQLite virtual table).
It's a function that would take a string and return a table with all the words of the string.
If I call it with literal values like below, it works fine.
SELECT word FROM splitstring("abc def ghi")
If, however, I call it with a column from another table it doesn't work:
SELECT a.Name, word FROM article a, splitstring(a.Text)
The xBestIndex method gets called all right, but right after that, I get an exception from the ExecuteReader method. The exception message is "xBestIndex malfunction". The xFilter method does not get called because of the exception.
My xBestIndex implementation is simple, it just marks the parameter so I can see it in xFilter:
public override SQLiteErrorCode BestIndex(SQLiteVirtualTable table, SQLiteIndex index)
{
index.Outputs.ConstraintUsages.ElementAt(0).argvIndex = 1;
index.Outputs.ConstraintUsages.ElementAt(0).omit = 1;
return SQLiteErrorCode.Ok;
}
Am I'm doing something wrong or is it impossible to pass non-literal parameters to table valued functions?
Found the issue! I was using constraints that had usable=0. The BestIndex method gets called multiple times by SQLite, the second time with a non-usable constraint.
Here is the fixed body of the BestIndex method.
public override SQLiteErrorCode BestIndex(SQLiteVirtualTable table, SQLiteIndex index)
{
if (index.Inputs.Constraints.Count() != 2)
throw new ArgumentException("The generate_series function requires two integer (long) parameters!");
if (index.Inputs.Constraints.All(c=>c.usable == 1))
{
index.Outputs.ConstraintUsages.ElementAt(0).argvIndex = 1;
index.Outputs.ConstraintUsages.ElementAt(0).omit = 1;
index.Outputs.ConstraintUsages.ElementAt(1).argvIndex = 2;
index.Outputs.ConstraintUsages.ElementAt(1).omit = 1;
}
else
{
index.Outputs.IndexNumber = -1;
index.Outputs.EstimatedCost = double.MaxValue;
}
return SQLiteErrorCode.Ok;
}
Now I check the usable flag. When BestIndex gets called with a constraint with usable=0 I skip it i.e. return a high estimated cost for that index so it doesn't get used.

Using find() to match multiple conditions

I have been using this code to find whether a school exists in a collection or not
var sn = 'mit';
var schoolexists = Schools.find({schoolname: sn}, {limit: 1}).count() > 0;
if(schoolexists == true){
alert('school already exists');
}
This works but i now need to introduce two more pointed conditions like schoollocation,studentid and get only the records that satisfy those three conditions. How would i introduce the two extra conditions?.
Just add them to the selector (the first argument):
var selector = {
schoolName: 'mit',
shoolLocation: 'cambridge',
studentId: 'abc123'
}
var schoolexists = Schools.find(selector, {limit: 1}).count() > 0;
Selector fields are ANDed together.

Faster database access by index

I have this code
using (var contents = connection.CreateCommand())
{
contents.CommandText = "SELECT [subject],[note] FROM tasks";
var r = contents.ExecuteReader();
int zaehler = 0;
int zielzahl = 5;
while (r.Read())
{
if (zaehler == zielzahl)
{
//access r["subject"].ToString()
}
zaehler++;
}
}
I want to make it faster by accessing zielzahl directly like r[zielzahl] instead of iterating through all entries. But
r[zielzahl]["subject"]
does not work aswell as
r["subject"][zielzahl]
How do I access the column subject of result number zielzahl?
To get only the sixth record, use the OFFSET clause:
SELECT subject, note
FROM tasks
LIMIT 1 OFFSET 5
Please note that the order of returned records is not guaranteed unless you use the ORDER BY clause.

Resources