How to write a RavenDB index as a prefiltered list of documents, not searchable - ravendb

I want to get a list of users filtered by a property (string) being null or empty.
I've created an index for this but I'm not sure if my way of implementing it is the right way to do it.
public class Users_Contributors : AbstractIndexCreationTask<User>
{
public Users_Contributors()
{
Map = users => from user in users
where user.ContributionDescription != null && user.ContributionDescription != ""
select new {};
}
}
So I just want raven to "prepare" the list of users for me. I'm just gonna get all user objects out of that index with no additional filtering/where criterias at query time.
Is the above code the way to go or can I achieve the same in a better way? Im feeling Im missing something here. Thanks!

This will work just fine. The result would be that the index only contains users that have something in their ContributionDescription field.
If you want to make it slightly easier to read, you can use string.IsNullOrEmpty, but that won't have any impact on performance.
Map = users => from user in users
where !string.IsNullOrEmpty(user.ContributionDescription)
select new {};
It probably feels strange because of the empty object at the end, but that just defines the index entries. If you aren't sorting or filtering by any other field, then using an empty object is just fine. Keep in mind that the __document_id entry gets created regardless of what fields you map.

Related

How do I implement, for instance, "group membership" many-to-many in Parse.com REST Cloud Code?

A user can create groups
A group had to have created by a user
A user can belong to multiple groups
A group can have multiple users
I have something like the following:
Parse.Cloud.afterSave('Group', function(request) {
var creator = request.user;
var group = request.object;
var wasGroupCreated = group.existed;
if(wasGroupCreated) {
var hasCreatedRelation = creator.relation('hasCreated');
hasCreatedRelation.add(group);
var isAMemberOfRelation = creator.relation('isMemberOf');
isAMemberOfRelation.add(group);
creator.save();
}
});
Now when I GET user/me with include=isMemberOf,hasCreated, it returns me the user object but with the following:
hasCreated: {
__type: "Relation"
className: "Group"
},
isMemberOf: {
__type: "Relation"
className: "Group"
}
I'd like to have the group objects included in say, 'hasCreated' and 'isMemberOf' arrays. How do I pull that using the REST API?
More in general though, am I approaching this the right way? Thoughts? Help is much appreciated!
First off, existed is a function that returns true or false (in your case the wasGroupCreated variable is always going to be a reference to the function and will tis always evaluate to true). It probably isn't going to return what you expect anyway if you were using it correctly.
I think what you want is the isNew() function, though I would test if this works in the Parse.Cloud.afterSave() method as I haven't tried it there.
As for the second part of your question, you seem to want to use your Relations like Arrays. If you used an array instead (and the size was small enough), then you could just include the Group objects in the query (add include parameter set to isMemberOf for example in your REST query).
If you do want to stick to Relations, realise that you'll need to read up more in the documentation. In particular you'll need to query the Group object using a where expression that has a $relatedTo pointer for the user. To query in this manner, you will probably need a members property on the Group that is a relation to Users.
Something like this in your REST query might work (replace the objectId with the right User of course):
where={"$relatedTo":{"object":{"__type":"Pointer","className":"_User","objectId":"8TOXdXf3tz"},"key":"members"}}

Eloquent: Get pages based on user role

I have a User, Role & Page setup, all with many-to-many relationships and the pivot tables setup in the usual fashion (role_user, page_role), along with the eloquent methods to attach a model to the pivot tables.
My idea is to allow a user to have many roles, and a page can be accessed by many roles.
However now I'd like to return a collection where I have my users details and then the pages they're allowed to access.
The closest I have got is:
return User::find( Auth::user()->id )->with('roles.pages')->first()->roles;
Now this returns each role the user has, and each page that the role can access. Which is correct, however I have duplication on the pages part.
How would I go about getting only a list of pages the user is able to access with no duplication?
Cheers
Read that answer to get you on the track: HasManyThrough with one-to-many relationship
Only for your setup you need to adjust the query - join 2 pivot tables (and make sure they represent real data, ie no rows referencing non-existing models):
// User model
// accessor so you can access it like any relation: $user->pages;
public function getPagesAttribute()
{
if ( ! array_key_exists('pages', $this->relations)) $this->loadPages();
return $this->getRelation('pages');
}
// here you load the pages and set the collection as a relation
protected function loadPages()
{
$pages = Page::join('page_role as pr', 'pr.page_id', '=', 'pages.id')
->join('role_user as ru', 'ru.role_id', '=', 'pr.role_id')
->where('ru.user_id', $this->id)
->distinct()
->get(['pages.*', 'user_id']);
$hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Page::query(), $this, 'user_id', 'id');
$hasMany->matchMany(array($this), $pages, 'pages');
return $this;
}
One more thing: I hardcoded tables and columns names for sake of simplicity, but in real life I suggest you rely on the relationships and their getters, like: $relation->getTable(), $relation->getForeignKey() etc.
Now suggestion about your code:
return User::find( // 2. query to get the same user
Auth::user()->id // 1. query to get the user and his id
)->with('roles.pages')
->first() // 3. query to get ANOTHER user (or the same, luckily..)
->roles;
Use Auth::id() instead of Auth::user()->id (for Laravel ver 4.1.25+) to avoid redundant query
find() and first() are methods that execute the query, so you just returned the user with id = Auth::user()->id and moment later you fetch another one, who comes first() from the users table..
You don't need to use User::whatever for authenticated user, use Auth::user() instead.
So the code with suggested solution would look like this:
Auth::user()->pages; // collection of Page models with unique entries

Linq order by with a field to retrieve dynamically in vb.net

I have a object Ob with several fields f1,..,fn (of different types).
Now a list of object is shown in a GridView and I need to implement the sorting method.
The real problem is:
how can I run
(from ob in Ob_list orderby ob.f1 ascending)
when the sorting field is represented by a string (i.e. "f1")?
Unfortunately I am not able to get it with the reflection (I am not able to do something like ob.GetType().GetField("f1"), this is not mapped into sql code).
I have several fields to possibly sort the rows, which is the best&fastest approach to this?
Thank you very much!
LINQ execution is deferred until you actually enumerate over the results or access the "count", etc. Because of this, you can build up your LINQ statement in stages.
The below code is done in C#, but I'm sure the equivalent is possible in VB.NET.
First setup your basic query:
var query = (from ob in Ob_list);
At this point, nothing has actually gone to the database due to deferred execution.
Next, conditionally add your order by components:
if (sortField == "f1")
{
query = query.OrderBy(o => o.f1);
}
else if (sortField == "f2")
{
query = query.OrderBy(o => o.f2);
}
else
{
//...
}
And finally, collect your results
foreach (var item in query)
{
// Process the item
}
I've found this question: How do I specify the Linq OrderBy argument dynamically?
I'm using Entity Framework, so the first answer did not solved my problem. The second one however, worked great!
Hope it helps!

Eloquent many-to-many with filters on both sides

I've been reading the docs but I"m not sure how to do this. http://doc.laravelbook.com/eloquent/#many-to-many
Say I have a users, roles, and a pivot table.
I have belongsToMany set up for both Role and User
In a controller, I want to get a user_id and return what roles they have of a specific type only.
(There is also a role type table, but I can work with the IDs directly).
I start something like this
$specific_type_role = Role::where('role_type_id', 3)::where(?$user_id?)
//need to involve
$circle_users = RoleUser::where('user_id', $user_id)->get();
but I think it should be able to be done automatically. don't know how to include the filter right in the query.
Not sure if it's that what you need but, you probably will be able to do something like that:
public function getAdminRoles()
{
$user = User::find(1);
return $user->roles()->where('role_type_id', 1)->get();
}

permanently sorting a collection

I have an observable collection that is exposed to the user by a collectionviewsource. One of the properties on the items in the collection is sortorder. I am trying to allow the user to permanently resort this collection and propagate the changes to the db.
I have the CVS working where I can resort the individual items as they are displayed in the listbox. Now however I have to change the item.sortorder==cvs.currentindex and i am having trouble figuring out the proper way to do this.
EDIT
evidently I was not clear enough. Sortorder is a field in my DB that is part of my object that allows the user to control position of the items as displayed in list controls. I am trying to give my user the ability to change how these items are sorted in the future by changing the value of the sortorder field to equal the current index of the displayed item.
items current sortorder value is 3.
user moves displayed listitem to position 0(ie first position)
items new sortorder=0 item with original sortorder will become 1 etc
this would be achieved by looping through the sorted CVS and making Item.SortOrder= CVS.Item.index
Databases return rows from table based typically on the order they were added to the table unless you specify an order by clause in your query. changing the order in the database is not a good idea. instead, try something such as using a parameterized query and passing in the column and direction you wish to be sorted which is retrieved from a user preference.
I figured it out.
I went back and looked at the code that I was using to change the position of the elements and I am actually using the collection itself:
private void OnDecreaseSortOrderCommandExecute()
{
int index = QuestionsCVS.View.CurrentPosition;
QuestionsViewModel item = SelectedQuestionVM;
if (item != null && index > 0)
{
SortableQuestionsVMCollection.RemoveAt(index);
SortableQuestionsVMCollection.Insert(index - 1, item);
QuestionsCVS.View.Refresh();
QuestionsCVS.View.MoveCurrentTo(item);
}
}
So I simply did this:
private void ResortSortableQuestionsVMCollection()
{
for (int i = 0; i < SortableQuestionsVMCollection.Count; i++)
{
SortableQuestionsVMCollection[i].SortOrder = i;
}
}
I dont know if this will work in every circumstance but it certainly did what I wanted for this one.