Adonis-Js : Get a specifc number of Entities in relationship with another Entity - entity-relationship

I need your help in Adonis-Js for loading an an entity with relationships. Here is my problem :
I have two entities :
Contact (belongsTo Contactgroup)
Contactgroup (hasMany Contact)
I want to make a request to get the list of Contactgroup with some Contact in it, here is an exemple, this code gives me all Contactgroup with all Contact related to them. :
let ContactgroupList = await Contactgroup.query()
.where('profile_id', auth.user.id)
.with('contact')
.fetch();
In my case I just want to get all Contactgroup with only some Contact related to them (for exemple a maximum of 3 Contact for each Contactgroup found), but when I use the code below :
let ContactgroupList = await Contactgroup.query()
.where('profile_id', auth.user.id)
.with('contact', (builder) => {
builder.pick(3)
})
.fetch();
I get only the first 3 contact related to the first Contactgroup, exemple :
if Contactgroup[0] have X Contact -> it shows an array of the first 3 contact of it, and
if Contactgroup[1] have X Contact -> it will show an empty array.
How can I get 3 contact for each Contactgroup ?
I hope my explanation is clear, and thanks in advance for your help !

a friend of mine gave me the solution with using the eagerLoadQuery :
let ContactgroupList = await Contactgroup.query()
.where('profile_id', auth.user.id)
.with('contact', (builder) => {
builder.eagerLoadQuery((relationQuery, foriegnKey, groups) => {
relationQuery
.from('contacts as c')
.whereRaw('(select count(*) from `contacts` as c1 where c.contactgroup_id = c1.contactgroup_id AND c.id < c1.id) < 3')
.whereIn(`c.${foriegnKey}`, groups)
.orderBy('c.id', 'desc')
})
})
.fetch()
see also this post for more informations : Link

Related

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context

I have nurse and patient tables having a many to many relationship; thus, the third relationship table is nurse_patient consisting of n_id and p_id.
Once a nurse logins a session is created. I want to select all patients of this logged in nurse only. I tried the code below but it's giving the error shown in the title.
if (Session["LogedUserID"] != null)
{
int p = Convert.ToInt32(Session["LogedUserID"]);
var patients = db.patients.Where(a => a.nurse_patient.Select(x => x.n_id).Equals(p)).ToList();
return View(patients);
}
var patients = db.nurse_patient.Where(e => e.nurse.id == nid).Select(e => e.patient).ToList();
This solved it. Thanks

Parse.js + AngularJS app relational data query issue

I have two parse classes; Companies and Ratings. It is a one to many relationship. Companies can have many Ratings. This is the statement I would perform in SQL:
SELECT Companies.name, Ratings.rating
FROM Companies
INNER JOIN Ratings
ON Ratings.name_id = Companies.name_id
ORDER BY Companies.name
I want the equivalent of this in Parse, but I'm not sure of how to go about it. Here is what I've currently tried:
function getRatings() {
var tableA = new Parse.Query(Companies);
var tableB = new Parse.Query(Ratings);
tableB.equalTo("name_id", tableA.name_id);
tableB.find({
success: function(results) {
$scope.$apply(function() {
$scope.companies = results.map(function(obj) {
return {
id: obj.get("name_id"),
name: obj.get(tableA.name),
rating: obj.get("rating"),
parseObject: obj
};
});
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
I am calling this function when the controller loads. This code displays the rating in my output, but not the name of the company.
I am trying to get all the companies listed in the companies object, then pair them with all the ratings they have in the ratings object. Their common key is name_id. This is the code I am using within my Angular view:
<div class="span12">
<div ng-repeat="company in companies | filter: query | orderBy: orderList"
class="well company-description">
<h1>{{company.name}}</h1>
<h3>Rating: {{company.rating}}</h3>
</div>
</div>
If I am way off base on this, please let me know
Get rid of the name_id column in the Ratings class. This isn't how you're supposed to define relationship using Parse.
There are a couple of options for you to choose.
Option 1
Using the Parse data browser, add a new column under the Companies class, called ratings. It should be a column of type Relation and point to Ratings as the target class. (Let me know if you need more information on how to do this.)
Then, when you create or edit a company, add ratings as follows:
var Companies = Parse.Object.extend("Companies");
var Ratings = Parse.Object.extend("Ratings");
var company = new Companies({name: "Some Company"});
company.relation("ratings").add(new Ratings({stars: 5}));
company.save();
Then, when querying Companies, do so as follows:
new Parse.Query(Companies).find({
success: function(companies) {
for (var i = 0; i < companies.length; i++) {
companies[i].relation("ratings").query().find({
success: function(ratings) {
// Finally, I have the ratings for this company
}
}
}
}
});
Option 2
Using the Parse data browser, add a new column under the Companies class, called ratings. It should be a column of type Array.
Then, when you create or edit a company, add ratings as follows:
var Companies = Parse.Object.extend("Companies");
var Ratings = Parse.Object.extend("Ratings");
var company = new Companies({
name: "Some Company",
ratings: [new Ratings({stars: 5})]
});
company.save();
Then, when querying Companies, do so as follows:
new Parse.Query(Companies).include("ratings").find({
success: function(companies) {
// Yay, I have access to ratings via companies[0].get("ratings")
}
});
include("ratings") tells Parse to include the actual objects, rather than pointers to objects for the given key.
Conclusion
Option 1 is better if you are expecting to have a large amount of ratings for each company, and if you don't always plan on retrieving all the ratings each time you query the companies.
Option 2 is better if the number of ratings for each company is relatively small, and you always want ratings to come back when you query companies.
I found out how to resolve the Uncaught You can't add an unsaved Parse.Object to a relation. error.
var addRating = new Ratings({stars: rating}); // save rating first, then associate it with a company
addRating.save({
success: function() {
var addCompany = new Companies({name: name});
addCompany.relation("ratings").add(addRating);
addCompany.save();
}
});
The rating has to be saved first, then the company relation can be added later on... makes sense, but took me awhile to figure it out! :S

How can I get a specific Neo4j node using Neo4jClient

Some pseudo-code of the model I'm working with:
User { int Id, string Username }
Activity { int Id, string Name }
Place { int Id, string Name }
Basically I have a bunch of Users and they belong to certain places (many to many relationship in RDBMS world). What I'd like to do now that I've created all of the nodes already is create the relationship between them. To do that I believe I need to get references to each node and then simply create the relationship between them.
Note: So far no relationships exist. It does look like in some of the examples they have added the User nodes with a relationship that points to the RootNode but I have no idea why. I'm not sure if I need to do that or not.
More pseudo-code:
var userRef = _graphClient...GetUserNodeWhereIdEquals(user.Id);
// or something like _graphClient.OutV<User>("[[id={0}]]", user.Id)
// or even just _graphClient.V<User>(id == user.Id)
var placeRef = _graphClient...GetPlaceNodeWhereIdEquals(place.Id);
_graphClient...CreateRelationshipBetween(userRef, placeRef, "belongs_to");
Unfortunately the documentation starts off pretty great then goes south when you get to relationships.
Update 3/29/12
Here's the code I have so far:
foreach (var a in _activityTasks.GetAll())
{
_graphClient.Create(a, new ActivityBelongsTo(_graphClient.RootNode));
}
foreach (var p in _placeTasks.GetAll().Take(1))
{
var placeNode = _graphClient.Create(p, new PlaceBelongsTo(_graphClient.RootNode));
foreach (var activity in p.Activities)
{
Activity activity1 = activity;
var activityNode = _graphClient.RootNode.In<Activity>(ActivityBelongsTo.TypeKey, a => a.Id == activity1.Id).SingleOrDefault();
_graphClient.CreateRelationship(placeNode, new PlaceHasActivity(activityNode.Reference));
}
}
The activity nodes are created fine. The place node is created fine. An error is now being thrown when trying to get the activityNode. It's a rather large stack trace so I'll try to paraphrase here:
Received an exception when executing the request.
The query was: g.v(p0).in(p1).filter{ it[p2] == p3
}.drop(p4).take(p5)._()
The exception was: Value cannot be null. Parameter name: key
System.ArgumentNullException: Value cannot be null.Parameter name: key
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue
value, Boolean add) ... The raw response body was: [ {
"outgoing_relationships" :
"http://localhost:7474/db/data/node/2/relationships/out", "data" : {
"Name" : "Aerobics", "Id" : 2 }, "all_typed_relationships" :
"http://localhost:7474/db/data/node/2/relationships/all/{-list|&|types}",
"traverse" :
"http://localhost:7474/db/data/node/2/traverse/{returnType}", "self"
: "http://localhost:7474/db/data/node/2", "property" :
"http://localhost:7474/db/data/node/2/properties/{key}",
"outgoing_typed_relationships" :
"http://localhost:7474/db/data/node/2/relationships/out/{-list|&|types}",
"properties" : "http://localhost:7474/db/data/node/2/properties",
"incoming_relationships" :
"http://localhost:7474/db/data/node/2/relationships/in", "extensions"
: { }, "create_relationship" :
"http://localhost:7474/db/data/node/2/relationships",
"paged_traverse" :
"http://localhost:7474/db/data/node/2/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships" :
"http://localhost:7474/db/data/node/2/relationships/all",
"incoming_typed_relationships" :
"http://localhost:7474/db/data/node/2/relationships/in/{-list|&|types}"
} ]
Something to do when adding a item to a Dictionary when the key is null. Problem is, I don't see any nulls when I debug on my end, activity1 is there, RootNode is there, TypeKey is a const string.
I'm almost wondering if I should just keep the created nodes within a array or Dictionary myself and then just working with the NodeReference. That's what I'm going to try next.
Later that morning
This seems to load everything into the graph database fine:
var activityNodes = _activityTasks.GetAll().ToDictionary(a => a.Id, a => _graphClient.Create(a, new ActivityBelongsTo(_graphClient.RootNode)));
foreach (var p in _placeTasks.GetAll())
{
var placeNode = _graphClient.Create(p, new PlaceBelongsTo(_graphClient.RootNode));
foreach (var activity in p.Activities)
{
_graphClient.CreateRelationship(placeNode, new PlaceHasActivity(activityNodes[activity.Id]));
}
}
foreach (var u in _userTasks.GetAllUserGraph())
{
var userNode = _graphClient.Create(u, new UserBelongsTo(_graphClient.RootNode));
foreach(var activity in u.Activities)
{
_graphClient.CreateRelationship(userNode, new UserParticipatesIn(activityNodes[activity.Id]));
}
}
Now the problem is similar to what I had before. Now I want to get an activity that has a relationship to the RootNode:
Node<Activity> activity = _graphClient
.RootNode
.In<Activity>(ActivityBelongsTo.TypeKey, a => a.Id == 1)
.SingleOrDefault();
Throwing the key value can't be null exception again. I think I need to investigate the gremlin syntax more. I'm guessing the problem is there.
This afternoon
Started to experiment with Gremlin queries:
g.v(0).inE.filter{it.label=="ACTIVITY_BELONGS_TO"}.outV.filter{it.Id==1}.Name
works fine. I tried to replicate that using neo4jClient syntax:
_graphClient.RootNode.InE(ActivityBelongsTo.TypeKey).OutV(b => b.Id == 1).SingleOrDefault();
Same null exception, it spits out:
g.v(p0).inE.filter{ it[p1].equals(p2) }.outV.filter{ it[p3] == p4 }.drop(p5).take(p6)._()
which looks right to me, except for the end. Ran this though:
g.v(0).inE.filter{it.label=="ACTIVITY_BELONGS_TO"}.outV.filter{it.Id==1}.drop(0).take(1)._()
And that works fine. Something stinks here...maybe I should try the other library although I liked the de/serialization support. Sigh...
Thought maybe a raw query would work. Nope! This method no longer accepts a string and the required GremlinQuery I have no idea how to you. Grooooooooooooooooan.
var users = graphClient.ExecuteGetAllNodesGremlin<IsCustomer>("g.v(0).out('IsCustomer'){it.'Name' == 'BobTheBuilder'}");
Update 3/30/12
Created a new project, everything below works fine. Super confused why it will work here... :( Maybe version differences, I have no idea.
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
client.Create(new User { Id = 1, Username = "joe" }, new UserBelongsTo(client.RootNode));
client.Create(new User { Id = 2, Username = "cloe" }, new UserBelongsTo(client.RootNode));
client.Create(new Activity { Id = 1, Name = "Bocce Ball" }, new ActivityBelongsTo(client.RootNode));
client.Create(new Activity { Id = 2, Name = "Programming" }, new ActivityBelongsTo(client.RootNode));
var user = client.RootNode.In<User>(UserBelongsTo.TypeKey, u=>u.Id == 1).SingleOrDefault();
var activity = client.RootNode.In<Activity>(ActivityBelongsTo.TypeKey, a=>a.Id == 1).SingleOrDefault();
client.CreateRelationship(user.Reference, new Plays(activity.Reference));
user = client.RootNode.In<User>(UserBelongsTo.TypeKey, u => u.Id == 1).SingleOrDefault();
activity = client.RootNode.In<Activity>(ActivityBelongsTo.TypeKey, a => a.Id == 1).SingleOrDefault();
I'm just getting started too. I would suggest you check out this blog:
http://romikoderbynew.com/2011/07/30/neo4jclient-primer/
Also, check http://frictionfree.org and its source code (in the about section) for more examples.
Creating relationships on existing - as I understand, this is possible. However, it appears to be easier to associate nodes as you create them. From the blog:
You can also create relationships between existing nodes.
graphClient.CreateRelationship(customerNodeReference, new
Speaks(languageNode.Reference));
RootNode - I believe you need to start a query from a node, I don't think you can do a
SELECT * FROM ... WHERE
Therefore, it would make sense that you need to attach nodes to the root node. This is an example from the FrictionFreeApp:
var node = graphClient.Create(
user,
new UserBelongsTo(rootNode));

can anyone advice with getting count for amount of products in category for specified results with linq

I have created a set of search results, and I wish to create a filter of available cats, with the number of results within that filter. however I get the most strangest error when trying to do this.
Unable to create a constant value of type 'NAMESPACE.Models.Products'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
this is the code i have tried:
var cats = (from p in ctx1.SubCategories
where myCats.Contains(p.subCategoryId) && p.enabled
select new
AvailableSubCats
{
CategoryName = p.subCategoryName,
Id = p.subCategoryId,
TotalItems = model.Count(x => x.subCategoryId == p.subCategoryId)
}).Distinct();
Products is the object that is called model on the line of totalItems.
I have also tried this:
var cats = from c in ctx1.SubCategories
join p in model on c.subCategoryId equals p.subCategorySubId
group p by c.subCategoryName
into g
select new
AvailableSubCats
{
CategoryName = g.Key,
Id = 0,
TotalItems = g.Count()
};
with the same error, and dont like this because i dont know how to get the name of the category and its ID.
help much appreciated.
thanks
p.s I am using Entity framework 4.1, .net 4 and MVC 3, mysql
in short i am trying to run this in linq, but were the the products side is already a result
select c.*, (select count(productId) from Products where Products.subCategoryId = c.subCategoryId) as counter from SubCategories c
You could try turning your list of products into a list of subCategoryId's so EF can understand it. Something like:
var subCategoryIds = model.Select(m => m.subCategoryId);
var cats = (from p in ctx1.SubCategories
ctx1.SubCategories
where myCats.Contains(p.subCategoryId) && p.enabled
select new
AvailableSubCats
{
CategoryName = p.subCategoryName,
Id = p.subCategoryId,
TotalItems = subCategoryIds.Count(x => x == p.subCategoryId)
}).Distinct();

Entity Framework - Join on many to many

I have a simple many to many relationship and I am wondering how you get data out of it. Here is the setup
Tables
Media
Media_Keyword (many to many map)
Keyword
Here is the code I have:
public List<Keyword> GetFromMedia(int mediaID)
{
var media = (from m in Connection.Data.Media
where m.id == mediaID
select m).First();
var keys = (from k in media.Media_Keyword
select new Keyword {ID = k.Keywords.id, Name = k.Keywords.keyword});
return keys.ToList();
}
Is there a way to do this better?
Usually, I select right from the many-to-many map.
var keys = from k in Connection.Data.Media_Keyword
where k.MediaID == mediaID
select k.Keywords;
I've not used the entity framework specifically, but can't you just combine them like this?
public List<Keyword> GetFromMedia(int mediaID)
{
return (from m in Connection.Data.Media
from k in m.Media_Keyword
where m.id == mediaID
select new Keyword {ID = k.Keywords.id, Name = k.Keywords.keyword}).ToList();
}
Response to Kleinux (Don't know why i can't add a comment to your question)
Sure you can, but it's not necessarly a good things, because context giving you a new "keyword". Then, if you try to update this or something thinking that you will update, context gonna see it as a new keyword and would create a new one instead of updating it.
** UPDATE
Sorry for my english, i'm french, well not french but from Quebec. I'm giving my 110%!!

Resources