I've already read some topics here in stackoverflow, but I didn't found a solution to my problem...
I want do the sum of 'progress' field in all my models into a collection...
So in my collection file I have:
progressTotal: ->
total = _.reduce(#, ((memo, value) ->
memo + value.get('progress')
), 0)
return total
But I get that value is undefined ... why ? I've taken inspiration from here: Getting the sum of a collection (all models) with backbone.js but the solution doesn't work for me.
Any suggestion ? thank you
EDIT: Seems like if progress is a string...but in my db is a integer.
You should pass an array of models to reduce instead of collection, so just replace # with #models
progressTotal: ->
total = _.reduce(#models, ((memo, value) ->
memo + value.get('progress')
), 0)
return total
you can also use Backbone.Collection#reduce method
progressTotal: ->
return #reduce(((memo, value) ->
memo + value.get('progress')
), 0)
Related
Good day. Am trying to query my database to get the child of a child of a child. Every user has 2 children. Am using query builder. The requirements is not to use eloquent and eloquent relationships. But am struggling with it.
$firstchild= DB::table('users') - >where('parent_id', Auth::user() ->id) -> get() ;
$secondchild1 = DB::table('users') - >where('parent_id', $firstchild[0]->parent_id) -> get() ;
$secondchild2 = DB::table('users') - >where('parent_id', $firstchild[1]parent_id) -> get() ;
return view('home' ['firstchild' => $firstchild, 'secondchild1 ' => $secondchild1, 'secondchild2 ' => $secondchild2 , ])
It returns undefined offset 0 if the user child has no child. How do i do it if i want to get without any errors.
If I want to get the children of those children the query results gave, how will I do so?
Try this:
$firstchild = DB::table('users')->where('parent_id', Auth::user()->id)->get();
if ($firstchild->count() == 2) { //**Contains exactly 2 arrays inside the 'firstchild' collection.
$secondchild1 = DB::table('users')->where('parent_id', $firstchild[0]->parent_id)->get();
$secondchild2 = DB::table('users')->where('parent_id', $firstchild[1]->parent_id)->get();
}
return view('home', compact('firstchild', 'secondchild1', 'secondchild2'));
Hope it's helpful.
This question does it in Javascript, but I would have thought in Typescript I could do some kind of map/filter operation to do the same thing.
I have an array of objects called Room. Each Room has a property called Width (which is actually a string, eg '4m', '5m', '6.5m').
I need to check the entire array to see if all the widths are the same.
Based on that question I have this, but I was wondering if TypeScript has something better:
let areWidthsTheSame = true;
this.qp.rooms.forEach(function(room, index, rooms) {
if (rooms[index] != rooms[index+1]) areWidthsTheSame = false;
});
Any ideas?
FYI the linked question has a comment that links to these performance tests, which are interesting in the context of this question:
This can be done in the following way:
const widthArr = rooms.map(r => r.width);
const isSameWidth = widthArr.length === 0 ? true :
widthArr.every(val => val === widthArr[0]);
We first convert the rooms array to an array of widths and then we check if all values in widths arrays are equal.
I am creating a foreach loop with button attach (name)' for each model which is not connected to the base model with abelongsToMany` relation.
I have an array with IDs for a certain model
$attached_stages = $object->stages()->getRelatedIds()->toArray(); // output: 1, 2
Then I have all model instances for the same model,
$all_stages = Stage::orderBy('id', 'asc')->pluck('id')->all(); // output: 1,2,3,4 ... 6
$missing_stages = array_diff($all_stages, $attached_stages); // output: 3,4,5,6
My question: how to get a collection out of the $missing_stages array
The array is created as expected
My question (alternative solution)
What I am actually trying to get here is a collection of models which are not attached to the main $object with the stages() relation.
The relation is defined as follows:
public function stages()
{
return $this->belongsToMany('App\Models\Stage', 'lead_stage', 'lead_id', 'stage_id')->withPivot('id','status')->withTimestamps();
}
and I am unable to get my desired collection with this code:
$all_stages = Stage::get(); // output: collction 1,2,.... 6
$attached_stages = $object->stages(); // output: 1, 2
$missing_stages = $all_stages->diff($attached_stages); // expected output: 3,4,5,6
Note: I attempted to remove the pivot part in relation definition, but it didn't help, the diff method is not working for me. Nothing is cut from the collection.
Any help appreciated. Thx.
You can use whereNotIn() for your problem as:
$attached_stages = $object->stages()->getRelatedIds()->toArray();
$missing_stages = Stage::whereNotIn('id', $attached_stages)->get();
I've been looking already around for the answer with no luck.
Basically I am reviewing again the Addy Osmani guide to Backbone, and it seems I can't get through this code here.
var people = new Backbone.Collection;
people.comparator = function(a, b) {
return a.get('name') < b.get('name') ? -1 : 1;
};
var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});
people.add(tom);
people.add(rob);
people.add(tim);
console.log(people.indexOf(rob) === 0); // true
console.log(people.indexOf(tim) === 1); // true
console.log(people.indexOf(tom) === 2); // true
I don't see how people.comparator can reorder the collection even though is not called anywhere, plus how comes that returning 1 or -1 can reorder it.
Or is it implicitly called once the Collection is created or indexOf is called on the Collection itself?
From the backbone documentation:
By default there is no comparator for a collection. If you define a
comparator, it will be used to maintain the collection in sorted
order. This means that as models are added, they are inserted at the
correct index in collection.models.
So every time you call people.add(...) the collection uses the comparator that you have set with people.comparator = function(a, b) { ... } to insert the model in an ordered position.
I'm trying to filter a Collection, and then shuffle the filtered values.
I was thinking of using the where method Backbone provides. Something like:
myRandomModel = #.where({ someAttribute: true }).shuffle()[0]
However, where returns an array of all the models which match the attributes; and apparently shuffle needs a list to work with:
shuffle_ .shuffle(list)
Returns a shuffled copy of the list
http://documentcloud.github.com/underscore/#shuffle
Is there a way to turn my array of models into a 'list'? Or should I write some logic myself to get this done?
When the Underscore docs say list, they mean array. So you can use _.shuffle like this:
shuffled = _([1, 2, 3, 4]).shuffle()
Or in your case:
_(#where(someAttribute: true)).shuffle()
However, since you're just grabbing a single model, you could simply generate a random index instead of shuffling:
matches = #where(someAttribute: true)
a_model = matches[Math.floor(Math.random() * matches.length)]
The shuffle() and where() method are just a proxy in Backbone collections to the underscore method. Underscore methods still work on their own, with arrays as argument. Here is what I would do:
myRandomModel = _.shuffle(#.where({ someAttribute: true }))[0]
Reference: http://documentcloud.github.com/underscore/#shuffle
PS: #"mu is too short" is right however, to get a single model I would go the Math.random() way myself.
I put the following in my application.js file (using Rails 3):
Array.prototype.shuffleArray = function() {
var i = this.length, j, tempi, tempj;
if ( i === 0 ) return false;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
tempi = this[i];
tempj = this[j];
this[i] = tempj;
this[j] = tempi;
}
return this;
};
and now I can call shuffleArray() on an array of arrays. Leaving this unanswered for now though, since I would like to know if there is a better way to do it with Underscore/Backbone.
First in your collection you should have a filtered function
Like
var MyCollection = Backbone.Collection.extend ({
filtered : function ( ) {
Normally you will use _.filter to get only the models you wanted but you may also use the suffle as a replacement use this.models to get the collection models
Here shuffle will mix the models
var results = _ .shuffle( this.models ) ;
Then use underscore map your results and transform it to JSON
like so
results = _.map( results, function( model ) { return model.toJSON() } );
finally returning a new backbone collection with only results you may return only the json if that's what you are looking for
return new Backbone.Collection( results ) ;
note if you don't want to keep all data in collection for later uses you may use the following and ignore the view below ;
this.reset( results ) ;
}
});