How to do a Django query from a ManyToMany relationship? - django-models

So i have a table with vehicles in my DB, each vehicle has a relationship with an user in the Users table and each user has a company value. I need to get all the vehicles that have a user that has an specific compay value.
example: query = vehicles.users(company = company)

If the relationship between vehicles and users is ManyToMany, and the relationship between company and user is OneToOne, you could do:
query = vehicles.objects.filter(user__company__id="my_company_id")

Related

sequelize js multi level table casecade join

i'm going to select user detail as table structure.
Table user columns {user_id, region_id, user_name}
Table region columns {region_id, country_id }
Table country columns {country_id, country_name }
I've join table model as
db.user.hasOne(db.region, {foreignKey:"region_id", targetKey:"region_id"});
db.region.hasOne(db.country,{ foreignKey :"country_id", targetKey:"country_id" });
db.user.hasOne(db.country,{through:db.region,otherKey :"country_id", foreignKey :"user_id" });
Now i am going to select user detail contain region name and contain country name here is my controller
models.user.findAll(
{
include: [
{
model: models.region,
model: models.country
}
]
});
but this show user not associate with country
Please save me
it should be multi level join as your schema
models.user.findAll(
{
include: [
{
model: models.region,
include:[{model:models.country}]
}
]
});
provided that user belongsTo region , region belongsTo country
you can search more about relationships some examples are
One-to-one relationship: You, as a User, can have one (hasOne)
Profile. And of course the inverse also applies. Profile (belongsTo) a
User. A user can't have more than one profile and a profile can't
belong to multiple users.
Also
We can define the inverse of a hasOne relationship using the belongsTo method.

How to make column data unique for each user_id in ruby on rails

The problem is that I have a table customers with some customers related columns like customersID.
Also I have a column user_id So that the customers data only relate to one user.
class Customers
belongs_to :user
end
class Users
has_many :customers
end
Now I have the :unique on the customersID. But this makes every customerID unique all over the table.
What i want is that the customerID is unique per user_id.
Any idea or suggestions?
Edit: Question seems bit unclear.
I have a table users
user1
user2
user3
also i have a table customers where each customer get a user_id from the user who created him. The user can input a customerID, which should be unique for each user.
customerID=1 user_id1
customerID=2 user_id1
customerID=1 user_id3
customerID=3 user_id1
customerID=1 user_id2
...
I crud the customers data via #customers = current_user.customers in my CustomersController. The customerID is a simple t.integer "customerID"
It seems as if you want a Customer to have a User, is that correct? Try something like this:
class Customer
has_one :user
end
class User
belongs_to :customer
end
That way you can have a customer tied to one specific user_id. Then you could do something like this:
#customer = Customer.where(name: "company name").first
#user = #customer.user #this will find the customer's unique user
Why not force uniqueness of the pair Customer_id, iser_id via an index on your Customers table ? You could create a migration something like
add_index_to_costumers.rb
class AddIndexToCustomers < ActiveRecord::Migration
def change
add_index :customers, [:customerID,:user_id], unique: true
end
end
It should ensure at the database level that the pair customerID/user_id is unique. If I well understand your question it's what you expect.
Hope this helps
Cheers

How to manage user database when number of choices of user is random

I am creating a small playlist program on VB, which contains adduser, deleteuser and also user can modify its playlist.
My stupid question is, how do I manage user playlist? Consider I am using database, where should I add user?
As a new table in Database?
As a new Entry in some kind of Table which contains userID, Name and its undefined number of choices?
If I select option 2, what kind of datatype handles a integer set of undefined size?
Thank you.
You would create 3 tables:
Users table
-----------
userID
email
password
name
Playlist table
--------------
playlistID
userID
trackID
Tracks table
------------
trackID
trackName
You would then create relationship between the tables:
Users.userID 1-* Playlist.userID (1 to many)
Tracks.trackID 1-* Playlist.trackID (1 to many)
Then you would store the users choices in the playlist table.
To see a users tracks you could do:
SELECT Playlist.trackID, Tracks.trackName
FROM Playlist
JOIN Tracks ON Playlist.trackID=Tracks.trackID
WHERE Playlist.userID = 12
ORDER BY Tracks.trackName
This is the basics of relational database system and normalisation of data.
For more information see:
http://www.dreamincode.net/forums/topic/179103-relational-database-design-normalization/

SaaS- Tenant Specific Lookup Data in Shared Database

I am developing multitenant SaaS based application and going with Shared Database for storing all the tenant records with help of TenantId column.
Now the problem is i have some list of lookup records that needs to be shared for all the tenants. For example list of games.
GamesTable
Id
GameName
Also have another table used for storing only tenant specific records
TenantGames
Id
TenantId
GameName
The basic need is i want to use both table data and get the necessary details (Game_Name) while joining with another transaction table like UserGames. How can i achive this with this design? Here Game_Name can be either referred from Games Shared table or TenantSpecificGames table
Is there any other DB design which allows me to do mix both common master data and tenant master data with JOIN?
Basic requirement is keep common data and allow customization for the tenants if they want to add any new items.
This is the design I would then use.
Games
Id
GameName
IsTenantSpecific
SomeGameSpecificColumn
TenantGames
GameId
TenantId
SomeTenantSpecificColumn
AnotherTenantSpecificColumn
Then you can query that table in a Join with:
...
FROM
Games
INNER JOIN UserGames ON
UserGames.GameId = Games.Id
LEFT JOIN TenantGames ON
TenantGames.GameId = Games.Id
WHERE
TenantGames.TenantId = #tenantId OR
(
TenantGames.TenantId IS NULL AND
IsTenantSpecific = 0
)
Game specific fields can be put in the Games table. Tenant specific fields can be added to the TenantGames table, and those fields will be NULL if it is not a tenant specific customization.
We have a saas based database and we keep common data and tenant data in the same table.
Concept
GamesTable
Id NOT NULL
TenantId NULL
GameName NOT NULL
Add a unique key for TenantId and GameName
if TenantId is NULL you know it is common data
if TenantId is NOT NULL you know it belongs to a specific tenant and who exactly.
"Is there any other DB design which allows me to do mix both common
master data and tenant master data with JOIN?"
Yes
SELECT *
FROM GamesTable where TenantId = 'your tenant id'
UNION
SELECT *
FROM GamesTable where TenantId IS NULL -- common
This is a classic example of "many to many".
Table: Games
------------
GameID
GameName
IsMasterGame
TennantGames
------------------
GameID
TennantID
Tennants
------------
TennantID
...
To get the games for a given tennant, you would run a query like:
select *
from Games
where isMasterGame = true
union
select *
from Games g,
TennantGames tg
where g.GameID = tg.GameID
and isMasterGame = false
and tg.TennantID = $currentTennant
(Apologies for archaic join syntax)
The union allows you to ask two questions: which games apply to everyone (isMasterGame = true), and secondly which games apply to the current tennant (tg.TennantID = $currentTennant). Logically, tennant games cannot also be master games.
You can merge the tables leaving TenantId as NULL for records you wish to not be Tenant specific.
Games
Id
TenantId
GameName
The you can query that table in a Join with:
...
FROM
Games
INNER JOIN UserGames ON
UserGames.GameId = Games.Id
WHERE
Games.TenantId = #tenantId OR
Games.TenantId IS NULL
This will save you the trouble of ensuring that the Id is unique between the tables, unless you are using a UNIQUEIDENTIFIER for the Id.

Entity Framework 4: Mapping several assocation tables to entities

I am kind of new to Entity Framework and ORMs. I have a simple database schema that is kind of like this.
User:
Id
Name
Group:
Id
Name
Role:
Id
Name
There are many-many between groups and users. Also, there is many-many between users and roles. However, Roles are per group. So we could have the following:
User A belongs to Group 1 with Roles a,b,c and belongs to Group 2, but has Roles d,e,f.
So we have some association tables like so:
UserRoles:
UserId -> User.Id
RoleId -> Role.Id
UserGroups
UserId -> User.Id
GroupId -> Group.Id
GroupRoles:
GroupId -> Group.Id
RoleId -> Role.Id
So, in my entities I want to have a Role entitiy, a User entity with a collection of Roles and a Group entity with a collection of Users and a collection of Roles.
When I load a group, I want to only load the users in that group and only that users roles for that group.
So my question:
In the above example. How do I make it so when I load Group 1, I want to see User A with Roles a,b,c and NOT Roles d,e,f.
Thanks,
JR
You need to call something like Group.User.Roles to get all Roles the user belongs to in the Group. something like:
var group1 = objectContext.Groups.Where(x => x.GroupId == 1);
var userARoles = group1.Users.Where(x => x.UserId == "A").Roles;
Does this help you?

Resources