I'm working on a project where I use mysql-model and I don't really understand how models work when we have multiple tables.
I have some code on my model user.js:
var mysqlcon = require('../models/db_connexion');
var User_model = mysqlcon.extend({
tableName: "users"
});
var log_user = new User_model();
Some code ...
Then a function to find the user's role:
module.exports.findUserRole = function(userId,callback){
let findUserRoleId = "SELECT role_id FROM users WHERE id = "+userId;
log_user.query(findUserRoleId,function(err,rows,fields){
let role_id = rows[0].role_id;
let findRolesInfo = "SELECT role_name,role_power FROM roles WHERE role_id = " + role_id;
log_user.query(findRolesInfo,callback)
})
And when I call this function, it returns me what I want, but I don't understand why.
My User_model isn't normally using only the table "users" ? So why can I also access to the table "roles" ?
I've searched on the npm documentation and googled it, but didn't found anything, or I missed it.
Thanks for your explanation.
And sorry if I missed something with the presentation, that's my first post.
Related
first sorry for my english ;)
second my question :
describtion :
I have :
var mongoose = require('mongoose');
// define the schema for our user model
var userSchema = mongoose.Schema({
facebook : {
id : String,
token : String,
email : String,
name : String
}
});
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
to use it with passport on a node.js .
...
var User = require('../app/models/user');
i dont connect to mongodb , since i use mysql to store my sessions .
the only stuff i dont understand is the _id value , comes it from passport , or sessions ?
question :
what i have todo to get a user model (object) so it is working together with passport/session ? or are there some method i need anyway , so it is better to get the user model from mongoose ?
sincerley rakondark
The id (known as the ObjectId) is generated and set by MongoDB for each documents.
I believe it auto-increments while using MySQL for passport.
I have a document upload system where the user can add Distributees. These people have access to view these documents. I am having difficulty showing these shared files to the distributees.
Currently it finds the user logged in, finds the distributees shared (The distributees model has the user and id saved into it) then using this it searches for the documents with the found distributees (myshared).
However I get the error "Operator "==" cannot be applied to the type of int and list"
// GET: DocumentUps
public ActionResult DocumentsShared()
{
string currentUser = this.User.Identity.GetUserName();
var myshared = db.Distributees.Where(a => a.UserIdSaved == currentUser).ToList();
var mydocs = db.DocumentUps.Where(a => a.DocumentId == myshared).ToList();
return View(mydocs);
}
What im trying to do is'
find distributees for logged in user
find documents related to distributees
All you need is a simple join between distributees and documentUps.
Or something like this:
var myshared = db.Distributees.Where(a => a.UserIdSaved == currentUser).Select(x => x.DocId);
var mydocs = db.DocumentUps.Where(a => myshared.Contains(a.DocumentId)).ToList();
I have a self referencing many to many relationship on my User entity being they can have many followers or follow many other users.
I am now trying to write a query in the user repository which will determine if a user is following another user.
I tried to write the query directy on user_relations (the mapping table) but it would not let me as it not related to the user entity.
So I tried:
$query = $this->createQueryBuilder('u')
->select('count(u.id)')
->innerJoin('u.following', 'r')
->where('u.id = :userID')
->where('r.from_id = :followingID')
->setParameter('userID', $userId)
->setParameter('followingID', $followingId)
Which results in an error stating the user entity does not have a field named from_uid.
How the hell can I correctly achieve this?
You can use MEMBER OF doctrine keyword
$query = $em->createQuery('SELECT u.id FROM User u WHERE :followingID MEMBER OF u.following');
$query->setParameter('followingID', $followingId);
$ids = $query->getResult();
I have a big django MySQL database and im struggling to get this to work efficiently :
models.py :
class Category(models.Model)
name = models.CharField()
class Article(models.Model)
start_date = models.DateTimeField(...)
end_date = models.DateTimeField(...)
active = models.BooleanField(...)
categories = models.ManyToManyField( Category )
I'd like to get all the active categories based on Article queryset. I actually do it this way :
actives_articles = Articles.objects.filter(start_date__gt = datetime.datetime.today(), end_date__lt = another_date, active = True)
actives_categories = Category.objects.filter(article__in = actives_articles).distinct().order_by('name')
actives_articles return about 50k results so this is not efficient at all.
Any idea or pointers ?
Thanks !
I finally got something working with this :
now = datetime.datetime.now()
filters = {
'article__active': True,
'article__start_date__lte':now,
'article__end_date__gte':now,
}
categs = Category.objects.filter(**filters).distinct()
silly me and thanks Django !
I'm trying to figure out the best way to save a simple one-to-many relationship in Linq2Sql.
Lets assume we have the following POCO model (pseduo code btw):
Person has zero to many Vechicles.
class Person
{
IList<Vehicle> Vehicle;
}
class Vehicle
{
string Name;
string Colour;
}
Now, when i save a Person, i pass that poco object to the repository code (which happens to be L2S). I can save the person object fine. I usually do this.
using (Db db = new Db())
{
var newPerson = db.People.SingleOrDefault(p => p.Id == person.Id) ?? new SqlContext.Person();
// Left to right stuff.
newPerson.Name = person.Name;
newPerson.Age = person.Age;
if (newPerson.Id <= 0)
db.People.InsertOnSubmit(newPerson);
db.SubmitChanges();
}
i'm not sure where and how i should handle the list of vehicles the person might have? any suggestions?
using (Db db = new Db())
{
var newPerson = db.People.SingleOrDefault(p => p.Id == person.Id) ?? new SqlContext.Person();
// Left to right stuff.
newPerson.Name = person.Name;
newPerson.Age = person.Age;
// add vehicles.
Vehicle firstV = new Vehicle();
firstV.Name = "some name";
firstV.Person = newPerson; // need to do this to set the person Id on the vehicle.
newPerson.Vehicle.Add(firstV);
// now when you save the Person it should save the Vehicle list
// if you set Cascade save update on the list. (not sure how to do that in L2S
if (newPerson.Id <= 0)
db.People.InsertOnSubmit(newPerson);
db.SubmitChanges();
}
Now you may choose to construct the list of vehicles at another level , with the data that's coming from the interface.
But you need to remember that it's not enough to add the Vehicle to the list on the Person object , you also need to set the vehicles Person property to the person that has the vehicles.
Observation I'm not sure about this but when you do db.People.SingleOrDefault you might be loading the whole People table in memory . That's not something you want to do. Corrected by Slace in the comments.
All you need to do is ensure that there are the appropriate relationships set up within the database.
If your Vehicle table has a PersonId and there is a foreign key between them when you add them to the DBML Linq to SQL will detect that there is a relationship between them and create a Table<T> representation of the relationship.