has_many()#

relationalai.Property
#Property.has_many() -> None

Declare a property to be multi-valued.

Example#

Use .has_many() to declare a property to be multi-valued:

#import relationalai as rai

# Create a model named "pets" with Person and Pet types.
model = rai.Model("pets")
Person = model.Type("Person")
Pet = model.Type("Pet")

# Declare that the 'pets' property of the Person type is multi-valued.
Person.pets.has_many()

# Check that the 'pets' property is multi-valued.
print(Person.pets.is_multi_valued)
# Output:
# True

with model.rule():
    # Add a Person named Alice to the model.
    alice = Person.add(name="Alice")
    # Add a Pet to Alice's 'pets' property.
    alice.pets.add(Pet.add(name="Fluffy", type="cat"))

    # Add a Person named Bob to the model.
    bob = Person.add(name="Bob")
    # Add two Pets to Bob's 'pets' property.
    bob.pets.extend([
        Pet.add(name="Spot", type="dog"),
        Pet.add(name="Rex", type="dog")
    ])

In the example above, .has_many() is optional. alice.pets.add() and bob.pets.extend() work without it, automatically creating a multi-valued .pets property.

.has_many() is required when creating a Type from a Snowflake table or view where a column contains multiple rows for the same primary key:

#import relationalai as rai

model = rai.Model("students")

# Create a Student type from the 'students' table in the 'sandbox.public'
# Snowflake schema. The table has `id`, `course`, and `grade` columns and
# may have multiple rows for each student enrolled in multiple courses.
Student = model.Type("Student", source="sandbox.public.students")

# Declare that the 'course' property of the Student type is multi-valued.
# NOTE: This is required so that the 'course' property is treated as multi-valued.
Student.course.has_many()

# What courses is student 1 enrolled in?
with model.query() as select:
    student = Student(id=1)
    response = select(student.course)

print(response.results)
# Output:
#         course
# 0  Mathematics
# 1      History
# 2      Science

Without declaring Student.course.has_many(), the course property is treated as single-valued, and the query will return only one course per student.

See Also#