Laravel Collection Sorting Desc/Asc Based On Condition - laravel-8

I have laravel elqueont collection and i want to sort it based on condition on status value, if status == 3 the ordering will be id desc else the ordering will be id asc, help please.
trying to sort laravel collection based on condition on anthor column value

You can read all about collection sorting on the documentation. So lets say you have 2 conditions your code will look like this
$collection = Model::all();
if($condition == 1) {
$collection->sortBy('created_at');
} else {
$collection->sortByDesc('created_at);
}
This is just a general idea, you can share your code for further help.

Related

How to express a 'smaller than or equals' relation in Knex.js

In my back-end I'm using KnexJS with PostgreSQL and I have to build a Knex function using its SQL builder without the raw SQL.
It is the first time for me to use KnexJS and I got few issues.
What I have to build is as shown in the SQL example
UPDATE
feed
SET
status = 'SOME_STATUS'
WHERE
created_at <= 'SOME_TIMESTAMP'
AND conversation_id = 'ID';
This SQL is updating the table feed all columns with status and where two conditions are met.
In Knex what I tried as example code of my idea
answerPendingMessages(feeds) {
return this.tx(tableName).where({
conversationId,
createdAt <= timestamp // This not idea how to do in Knex ???
}).update({
status: 'ANSWERED'
})
}
In this above function my concern is how to actually convert the where part as one of the consitions is createdAt <= 'TIMESTAMP'
I understood that I can use where with an object but cannot understand how to include the <=
Also I should update the updatedAt column with the new timestamp but also that blocked me at the moment.
Te result in the end should that all columns which met the conditions are updated status to some some status and also a new updatedAt timestamp.
I'm not sure if there is a specific way with Knex to do so
This answer is to provide my goal for my previous question.
The script I'm showing is not doing anything and I don't know know to make it to work.
answerPendingMessages(feeds) {
if (isEmpty(feeds)) return Promise.resolve([]);
const { conversationId, createdAt } = feeds;
return this.tx(tableName)
.where(
columns.conversationId === conversationId,
columns.createdAt <= createdAt
)
.update({
[columns.status]: 'ANSWERED',
[columns.updatedAt]: new Date(),
});
}
What should happen here is that to update a table where I have two conditions but one of then is 'smaller than or equals' relation.
As the output of this should be that all rows where the 2 conditions are met are update status column.
Right now the script is not failing either success piratically nothing is happening.

Select documents from Fauna collection between two dates AND that satisfy another criteria

I am able to use the following code to retrieve documents from a Fauna collection that have a date which falls between start and end dates:
Paginate(Range(Match(Index("orders_by_date")) , start, end))
Is it possible to add another criteria to this statement to retrieve not only, in this case, orders between two dates but also have the field status = "completed".
Thank you
You can create an index that way:
CreateIndex(
{
name:'orders_by_date_status',
source:Collection("orders"),
terms: [{field:['data','status']}],
values:[{field:['data','order_date']},{field:['ref']}]
}
)
and query your collection with a query like this:
Paginate(
Range(
Match('orders_by_date_status','completed'),
[Date("2020-03-20")],
[Date("2020-06-20")]
)
)
to get back something like this:
{
data: [
[Date("2020-05-20"), Ref(Collection("orders"), "285246145700037121")],
[Date("2020-06-20"), Ref(Collection("orders"), "285246152717107713")]
]
}
Hope this answers your question.
Luigi

MVC update the database based on a non primary key value

I have a database table that looks like this:
My goal is to update my "unavail" table based on the ID of either the component, part, or item depending on which one is relevant in my situation.
For example, if the partID = 43 I want to add to the 'unavail' column
I first started working on this by trying this
db.OffSiteItemDetails.Find(sod.PartID).unavail += sod.comp_returned;
(Where sod.PartId = 43)
But I quickly realized it was just checking for where the "ID" was equal to 43 which isn't what I want. After some investigation I saw people suggesting using
db.Where(x => x.non-pk == value)
So I created this
db.OffSiteItemDetails.Where(x => x.componentID == sod.ComponentID);
But from here I don't know how to change my unavail table values.
This was a tough question to type so if you need more clarity just ask
foreach(var item in db.OffSiteItemDetails.Where(x => x.componentID == sod.ComponentID))
{
// item.unavail = [new value]
// db.Update(item);
// ...I don't know how you update the data in your database
}
Something like that?

Find a records containg a specific tag

I have a following DB schema:
User
- id
- name (String)
UserTag
- user_id
- tag_id
Tag
- id
- key (String)
And i also have a pretty complex users-search chain with a lot of where statements. I'm trying to figure out how to include one another where condition to my chain - filtering for users that has a specific tag assigned (ID of this tag is unknown, just it's key is known).
So, here is more or less how my code looks:
col = User.all
col = col.where('cats_count <= 0') if args[:no_cat]
col = col.where('dogs_count <= 0') if args[:no_dog]
col = col.where('other_pets_count <= 0') if args[:no_other_pet]
# ... tag logic filtering here ...
col = col.where('age > 100') if args[:old]
And i want to filter for a users, who has a Tag with key=non_smoking assigned. Ideally, i would love it to be database-engine independen, if that's important - i'm on sqlite/postgres.
Honestly i have completely no any ideas on how to deal with that, i probably lack some knowledge in SQL matter and then, in Rails/ActiveRecord.
You can specify joins and the put conditions on the joined tables. So maybe something like (untested, off the top of my head)
col.joins(user_tags: :tag).where(user_tags: { tag: { key: 'non_smoking' } })

NHibernate sorting (SQL as a second option)

I'm using NHibernate as my ORM and I'm trying to sort some data. The data needs to be retrieved paged.
Two of the columns in my Request table are UrgencyID and CreateDate. UrgencyID is a FK to the Urgency table with static data:
1 = Low, 2 = Normal, 3 = High, 4 = Critical.
I need to order my Requests in the following manner.
Critical Requests by CreateDate descending
All other requests by CreateDate descending
So my list of Requests should always have Critical by CreateDate desc at the top and then all other Requests (disregarding UrgencyID) by CreateDate desc
Is it possible to perform this sort order in NHibernate (using the Criteria API)?
If not, how would I do this in SQL? In a stored procedure?
EDIT: Solution thanks to both #DanP and #Michael Pakhantsov
Using the this_ prefix in the sql string as this is the default NHibernate prefix for the primary table selection.
public class OperatorJobQueueOrder : Order
{
public OperatorJobQueueOrder() : base("", true) { }
public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
{
return new NHibernate.SqlCommand.SqlString("case this_.JobRequestUrgencyID when 4 then 4 else 0 end desc, this_.CreatedDate");
}
}
You may be able to create a custom sort order to handle this through the critiera api; see this question for an example implementation.
IN SQL ORDER BY will be
ORDER by case UrgencyId when 4 then 4 else 0 end, CreateDate desc