Consider the following Ballerina code,
import ballerina/persist as _;
type Phone record {|
readonly string id;
string number;
boolean textOK;
boolean whatsappOK;
boolean callOK;
Person person;
|};
type Person record {|
readonly string id;
string name;
string[] email;
Phone[] phones;
House house;
|};
type House record {|
readonly string id;
int number;
Person[] owners;
boolean isRented;
Person[] residents;
|};
Following error is generated when the bal persist generate
command is used for the second relationship to a person from house. Is there something wrong with the above code?
% bal persist generate
ERROR: failed to generate types and client for the definition file(model.bal). the model definition file(model.bal) has errors.
ERROR [model.bal:(25:5,25:24)] the related entity Person does not have the corresponding relation field
The issue here is related to having two one-many relationships between Person and House entities. In this case, there should be a corresponding relation field for both of these relations in the entity Person. You can fix the above issue by changing the Person entity into the following form
type Person record {|
readonly string id;
string name;
string[] email;
Phone[] phones;
House ownedHouse;
House residence;
|};
In addition to the above approach, you can also use many-many associations for the above case. In this case, the model file would take the following form.
import ballerina/persist as _;
type Phone record {|
readonly string id;
string number;
boolean textOK;
boolean whatsappOK;
boolean callOK;
Person person;
|};
type Person record {|
readonly string id;
string name;
string[] email;
Phone[] phones;
HouseAssociation[] houses;
|};
type HouseAssociation record {|
readonly string id;
string name;
House house;
Person person;
boolean isOwner;
|};
type House record {|
readonly string id;
int number;
boolean isRented;
HouseAssociation[] person;
|};