HasOne
A one-to-one relationship represents a fundamental type of database association. As an example, consider a User model linked to a UserInfo model. To establish this connection, we define a method called userInfo within the User model. This userInfo method invokes the HasOne method and returns its output.
Usage
$getRelation
User? user = await User().find(1);
await user?.$getRelation('userInfo')
UserInfo userInfo = user?.userInfo;
Info
When eager is true the $getRelation do not need to call.
preload
Info
When eager is true the preload do not need to call.
related
User? user = await User().find(1);
UserInfo userInfo = await user?.related<UserInfo>('userInfo')?.where('foo', 'bar').getFirst();
Options
model
foreignKey
localKey
onQuery
@DoxModel()
class User extends UserGenerator {
@HasOne(UserInfo, onQuery: onUserInfoQuery)
UserInfo? userInfo;
static QueryBuilder<UserInfo> onUserInfoQuery(UserInfo q) {
return q.where('status', 'active');
}
}
Info
onQuery method must be a static method inside the model.