Model Relationships and Handling Passwords in Database Schema
00:00 So let's go to our schema, and right down here, we're gonna create our model. Model, password, and this one's gonna be a little simpler than most of them. We don't need a created ad. I don't think that really makes too much sense to have a created ad or updated ad. I mean, maybe you might care about that,
00:17 but yeah, it doesn't really feel that important to me. In fact, even an ID doesn't seem to be necessary here. So we're just going to have the hash, and we're gonna have the user and the user ID, and this is gonna be a one-to-one relationship,
00:33 and so that's why we have the at unique on the user ID, and that will act as our ID for the password. So we're just gonna look up the password by the user ID, and then we're gonna need, in our user model right here, we're gonna need a password field.
00:51 So password is a optional password. So if I go down here, all that red stuff is gone now. If I try to make this required, it's not super jazzed about that, and it says the relation field password on model user is required. This is no longer valid because it's not possible
01:10 to enforce this constraint on the database level. I actually really appreciate that. I appreciate that rather than Prisma just saying, oh, they said it's required, but we know it can't be enforced, but we're just gonna let them say it's required. No, instead they say, no, you got to make this optional because the database can't enforce this.
01:28 And think about that. The reason why this can't be enforced is because I can make a user, I have an insert statement, SQL statement, insert user. There's nothing in the database that will say, oh, well, you also have to insert a password at the same time. You just can't do that. And while that, at first glance, you might be like,
01:51 I don't really like that. Later on, we're actually going to have users who don't have passwords because they can authenticate through other means. And so this will actually end up working out just fine for us. But yeah, that's just one of those things. You have to accept that databases cannot enforce
02:10 the existence of a model, a sub-model. But as mentioned before, it's very important that you don't put the hash right on the user because you could accidentally select all the data. So it is good to separate these things. We just have to live with the fact that we cannot enforce that the password is required. I think that's okay.
02:30 So we've got our password hash. We've got our user relation. If the user's deleted or updated, then we cascade that delete. We don't need the password to stick around if the user is deleted. And yeah, then we have our password reference right here. So on the user, if we do end up selecting the password, we can get it by password,
02:47 which we will do when we want to authenticate the user, which we will do very soon.