Here is my data model.
I need to make the username column in the USER table as a unique column. But it should be unique with the company.
For example, Company A can have a username as James and Company B also can have a username as James.
To achieve this, my opinion is to make a unique constraint with username and company_id.
How can I do this?
You need to change your database adding company_id to users. then add a unique index (company_id,username) to your table.
user
----
user_id (PK)
company_id (UNIQUE INDEX)
emplyee_id
email
username (UNIQUE INDEX)
password
BUT i think you do not need a many to many relation,
could be a good idea to change your database removing the many to many reaction in this way:
company
-------
company_id (PK)
company_name
user
----
user_id (PK)
company_id
emplyee_id
email
username
password
From the data model, it is clear that, a user can belong to multiple companies and a company can have multiple users. So adding company_id to USER table will cause USER table to explode with lots of redundant user data for each company instance. The USER_COMPANY entity exists specifically to avoid this.
It is not advisable to handle this requirement using data model changes. The best way to handle this requirement is through application code or triggers.
The least inefficient way to achieve this through data model changes will be, to add username column in user_company table and synchronise user and user_company table for the user_name column across all DMLs throughout the application. That will again require lots of application code.
So the best solution is to leave it to the application and not disturb a good data model.
Hope this helps.
Related
I have a Users table that can store 8 different types of users. Depending on the user type, I have some other tables with the specific data set for it. So, I would like to use the ID from the Users table as a foreign key and primary key at the same time for those tables. But I am new at Laravel and I don't know how to do that to fit the conventions or, if it is not possible, how to do that when defining my models and one to one relations. Can someone help me? Thanks!
EDIT: Sorry, I think my explanation is not clear enough. Let's say I have 4 tables: users, user_types, customer_organzations, partners, and customers. I would like to use ID, that is PK of users, as a foreign key and primary key for tables customer_organizations, partners and customers, that have different information since they are different type of users in my application but all them login against users table. I don't care user_types table. I think I know how to deal with it.
You haven't given us much in terms of your table structure, so assuming you have a simple one-to-one relationship between a users table and a user_types table, the following would create the required relationship.
In your user_types table migration
$table->foreignId('user_id')->constrained();
The above will add your foreign key to the table and create the relationship back to the users table (this is done 'magically' using conventions so naming is important).
Then in your eloquent models, add the relationships between the models:
User.php
public function type()
{
return $this->hasOne(UserType::class);
}
UserType.php
public function user()
{
return $this->belongsTo(User::class);
}
I'm using Laravel 5.4 and have a model and table structure as follows:
users
-----
id
accounts
--------
id
holdings
--------
id
account_id (foreign key to account)
user_accounts
-------------
id
user_id
account_id
A user can have multiple accounts
An account can be shared by multiple users
Each account has multiple holdings
A user therefore indirectly has many holdings through their many accounts.
I need help to define a relation on the User model called "holdings" to get me all the holdings applicable to the user (based on the accounts they are linked to).
I've tried lots of different things and spent ages on google. I can get close with both belongsToMany and hasManyThrough, but they only seem to work for 3 table relationships where the intermediate table stores primary keys from the other tables. I can reduce my relationship to 3 tables (rather than 4) if I make use of the account_id foreign key on the holdings table to remove the need to join through the accounts table, however I can't seem to get this to work.
belongsToMany - holdings.id needs to be holdings.account_id:
select * from `holdings`
inner join `user_accounts` on `holdings`.`id` = `user_accounts`.`account_id`
where `user_accounts`.`user_id` = ?
hasManyThrough - user_accounts.id needs to be user_accounts.account_id:
select * from `holdings`
inner join `user_accounts` on `user_accounts`.`id` = `holdings`.`account_id`
where `user_accounts`.`user_id` = ?"
Well it's not strictly an answer as I was asking about laravel 5.4, but it is a possible solution.
It turns out I'm in luck as I came across this Laravel belongsToMany relationship defining local key on both tables which indicates the belongsToMany relationship has been enhanced in Laravel 5.5 to support this type of scenario.
I have upgraded my project to L5.5 and replaced my hack with the relation:
return $this->belongsToMany(Holding::class, 'user_accounts', 'user_id', 'account_id', null, 'account_id');
And am happy to say it seems to work perfectly - at least for basic gets which is my use case, I haven't tried any updates etc.
Thanks to #cyberfly and those who posted the answer above
i'm trying to get extra column as foreign key in laravel many to many relationship..here is my table structure
idcards
id,
name,
quality
id,
name
idcard_quality
id,
idcard_id
quality_id
related_id
in above idcard_quality table i want add extra foreign key related_id, i wanted to retrieve result like every idcard hasmany qualities and that quality is another idcard.. suppose one idcardcard has one normal quality and that normal quality is different idcard...
please help me
I think your table design should look like this:
idcards
id,
name
quality
id,
name,
related_id
idcard_quality
idcard_id
quality_id
This way when you retrieve the values of the parent/related id card on joining the tables.
I am trying to implement an entity relation for a hospital oracle database system.
I am rather confused if I should seperate the table below or merge them into 1.
- Supply
ItemNo (PK) , Name, ItemDescription, QuantityInStock, BackOrderLevel, CostPerUnit
- PharmaceuticalSupply
DrugNo (PK) , Dosage, MethodOfAdmin
Basically in my ERD, I pointed PharmaceuticalSupply to Supply as a subset which inherits the attribute but also have additional attributes. Am I wrong in doing that?
Ultimately, this is a design decision that has no right or wrong answer, but keeping them separate can be helpful. For example, there are many types of supplies that are not pharmaceutical. If you merge the tables, you make it possible to enter data that has no real meaning. For example, you can't have a dosage of bandages. The separate table makes it clear that dosage only applies to pharmaceuticals.
Note that there are a few variations on how to manage the PKs and FKs in PharmaceuticalSupply. It could have both an ItemNo and a DrugNo, where ItemNo is a foreign key. In that case, either one could be the primary key, but if DrugNo is the primary key, then ItemNo probably needs to be a unique index. However, unless DrugNo is needed due to some custom format, it might work well to simply use ItemNo as both PK and FK and completely eliminate DrugNo. This results in a "specialization" as the relational database world likes to refer to it.
It depends on your population. It it's a subset, to reduce redundancy add a foreign key to Supply. That way you'll be able to build a join that list all data.
I would still introduce a DrugNo key for indexing. Can an item number appear more than once in the PharmaceuticalSupply table ? If your do then your definitely need the DrugNo key.
PharmaceuticalSupply
DrugNo (PK) , ItemNo (FK), Dosage, MethodOfAdmin
I have been able to make 2 ActiveRecord tables, Profile and Bot. I have been unable to figure out how to link them properly.
There are thousands of Profiles with columns username, gender. A handful of Bots with columns botname, level
When a bot visits a profile two pieces of info need to be recorded. visited and response should be updated for that specific bot. visited is a boolean that will indicate that one particular bot has visited that one particular profile. the response is a string, again like the visited this is a response for one particular bot that was sent by one particular profile. I am thinking I need a 3rd table that joins these two tables.
I need to keep a record of every profile that every bot visits and the response that happens when it visits.
How can I create this relationship and how can I set/update the columns?
Thanks
I'm not completely certain of your requirements, so I will restate them:
Table Profile: id, username, gender (note that I changed the table names to singular)
Table Bot: id, botname, level
The "bots" somehow "visit" profiles. You need to track when a bot has visited a profile.
When a bot visits a profile, a "response" string is generated and that response string needs to be preserved. I'm assuming it needs to be preserved with the record of the visit.
I think your instincts about a join table are good. I don't think a boolean "visited" column works, however, because if you have a record of a visit, that's an indication that the profile was visited. If the record doesn't exist, then it wasn't visited.
Given this, I think your tables look like this:
profile
---------
profile_id integer autoincrement
username varchar(255)
gender ...
bot
---------
bot_id integer autoincrement
name varchar(255)
level ...
visit
---------
visit_id integer autoincrement
bot_id integer
profile_id integer
visit_time datetime
response varchar(255)
To maintain the integrity of your data, you'll want to set up foreign key constraints between this visit table and your profile and bot tables.
alter table visit
add constraint visit_profile_profile_id_fk
foreign key (profile_id)
references profile (profile_id);
alter table visit
add constraint visit_bot_bot_id_fk
foreign key (bot_id)
references profile (bot_id);
You'll need to decide if it's "legal" for a given bot to visit a particular profile more than once. If it's not, you should put a unique constraint on the combination of profile_id and bot_id in the visit table, and catch the duplicate key errors when your DBMS throws them at you (or otherwise handle dupes.)
I hope that helps.