Type.define()#
#Type.define(self, **kwargs: tuple[Type, str, str]) -> None
Defines properties for a type based on foreign key relationships to other types.
Parameters#
| Name | Type | Description |
|---|---|---|
**kwargs | tuple[Type, str, str] | Keyword arguments where keys are the names of the new properties. Values are tuples representing a foreign key relationship, which include:
|
Returns#
None.
Example#
Use Type.define() to associate objects of one type with objects of another type based on a foreign key relationship.
.define() creates single-valued properties by default.
If you intend to assign multiple objects to a property created using .define(), you must explicitly declare the property as multi-valued using Property.has_many().
For example, an Employee type defined from a Snowflake table might have a department_id property that references Department objects by their id property.
You can define a department property for Employee objects that connects them to the related Department objects via the department_id property:
#import relationalai as rai
# =====
# SETUP
# =====
model = rai.Model("EmployeesModel")
# Declare Employee and Department types from Snowflake tables.
Employee = model.Type("Employee", source="<db>.<schema>.employees")
Department = model.Type("Department", source="<db>.<schema>.departments")
# =======
# EXAMPLE
# =======
# Define a property named 'department' for Employee objects that connects them
# to Department with the same id as the employee's department_id.
Employee.define(department=(Department, "department_id", "id"))
# Related department objects can be accessed directly in rules and queries using
# the 'department' property.
with model.query() as select:
employee = Employee()
employee.department.name == "Sales"
response = select(employee.name)
print(response.results)
# name
# 0 Jim
# 1 Dwight
# 2 Phyllis