backbone.js sortBy cid - sorting

I'm using backbone.js and trying to sort a collection by cid. How do I sort by cid??
I can sort it by attribute like 'name':
this.collection.sortBy("name")
this works.
But when I try to do this:
this.collection.sortBy("cid")
it returns a collection but its not sorted, its just the same as before.
and I tried this:
this.collection.sortBy(cid)
this returns an error obviously.
Any help??

sortBy sorts based on either an attribute on the model, or an iterator. Since cid is directly on the model and not an attribute, you need to use the iterator.
this.collection.sortBy(function(model){
return model.cid;
});

Related

How can i sort a laravel's elequent list by another ids

I have a challenge that if I want to sort the records when getting using Laravel's ORM based on a list of IDs, how should I do it?!!!!!!!
I mean :
Suppose we have a table called users, which contains 100 records and each record has a unique ID.
We also have an array of IDs.
$ids = [4,1,2,3]
Now I want to get the list of users, but only the users who are first in the ids array and secondly according to the same order as they are listed in this array.
User::whereIn('id' , $Ids)->sortBy('id',$ids)->get();
Can you think of a solution to do this?
User::whereIn('id' , $Ids)->sortBy('id',$ids)->get();
The collections sortBy() function can take a custom call back this way:
$users = User::whereIn('id', $Ids)->get()
->sortBy(function($user, $key) use($ids) {
return array_search($user->id, $ids);
});
This will sort your collection according to the given array.
You can also reference the docs for more information.
Note that the sortBy() function must act upon a collection, which means that the get() function must come before it.

Laravel merge collections and sort by value

I am looking to merge two Laravel collections and sort them by a field name. Here is what I did to get two collections.
$bills = BillLine::where('item_id',$this->item_id)
->join('bills', 'bill_lines.bill_id', '=', 'bills.id')
->select('bill_lines.confirmed_on','bill_lines.qty','bills.serial')
->get();
$invoices = InvoiceLine::where('item_id',$this->item_id)
->join('invoices', 'invoice_lines.invoice_id', '=', 'invoices.id')
->select('invoice_lines.confirmed_on','invoice_lines.qty','invoices.serial')
->get();
Now I want them to be merged and sorted by the confirmed_on field. This way I can loop them in the blade table. I tried and couldn't. Then I tried converting these two to arrays and merge them which is possible using array_merge() but sorting becomes the issue.
how to merge two collections
once merged in can use sortBy on collection to get it sorted.
You can merge collections using the merge() method.
Be aware though, that if a string key of the merged collection matches a string key in the original collection, it will override the entry in the original collection. To prevent that from happening, I think you can call values() method on both collections before merging, so the keys are reset to consecutive integers.
After the collections are merged, you can simply call sortBy method.
Example:
$bills->merge($invoices)
->sortBy('confirmed_on');

Laravel retrieve only specific fields from each item of collection

I may be missing something extremely trivial, but is it possible to retrieve specific columns/fields from models when grabbing a collection rather then returning the entire item's fields?
Here is my query:
$items = Items::where('visible', true)->take(10)->get();
This obviously returns each item in there entirety, including unique id's, and other fields i dont want to be fetched... how can i refine this query to just select specific fields from the models?
Laravel Query Builder get() function receives array of columns which you need to fetch.
$items = Items::where('visible', true)->take(10)->get(['column_1', 'column_2']);
Use select() method to do this:
$items = Items::select(['column_1', 'column_2']'])->where('visible', true)->take(10)->get();
Source: Latavel Database Query Builder
Laravel Query Builder gives a huge flexibility to write this types of query.
You can use select(), get(), all() methods.
Items::where('visible', true)->take(10)->get('col_1', 'col_2');
OR
Items::select('col_1', 'col_2')->where('visible', true)->take(10)->get();
Items::select(['col_1', 'col_2'])->where('visible', true)->take(10)->get();

Fetch the value of a given column in Eloquent

I am trying to get the value of a single column using Eloquent:
MyModel::where('field', 'foo')->get(['id']); // returns [{"id":1}]
MyModel::where('field', 'foo')->select('id')->first() // returns {"id":1}
However, I am getting anything but the value 1. How can get that 1?
NOTE: It is possible that the record with field of foo does not exist in the table!
EDIT
I am ideally looking for a single statement that either returns the value (e.g. 1) or fails with a '' or null or other. To give you some more context, this is actually used in Validator::make in one of the rules:
'input' => 'exists:table,some_field,id,' . my_query_above...
EDIT 2
Using Adiasz's answer, I found that MyModel::where('field', 'foo')->value('id') does exactly what I need: returns an integer value or an empty string (when failed).
Laravel is intuitive framework... if you want value just call value() method.
MyModel::find(PK)->value('id');
MyModel::where('field', 'foo')->first()->value('id');
You're using the Eloquent query builder, so by default, it'll return an Eloquent model with only the value you wish.
The method you're looking for is pluck() which exists in the normal query builder (of which the Eloquent one extends) so your code should look as follows:
MyModel::where('field', 'foo')->pluck('id'); // returns [1]
The value() method that is being used in the other answers is an Eloquent model method. Using that means that the framework queries the database, hydrates the model and then returns only that value. You can save yourself a few keystrokes and few CPU cycles by using pluck() and have it handled simply in one query.

Sortby Collection BackboneJS With Lodash

I have collection like this:
child{length:3, models:array[3], _byId:Object}
I wanna sort models array, I use lodash like this:
var array_of_objects = new ListCollection();
var data = _.sortByOrder(array_of_objects.models, ['id'], ['asc']);
And I get result only:
[child, child, child]
How to sort models arrays with keep length and the Object.
If you want to order the original collection, set collection.comparator to 'id' and then call collection.sort().
To order the models without affecting the collection do: _.sortBy(collection.models, 'id')
Note that these will order the Models, not native js arrays. If your looking to operate on a raw collection of arrays, get a copy of the collection with var models = JSON.parse(collection.toJSON()) and then follow the instructions for _.sortBy.

Resources