Red — relationship

Relationships

Relationships in Red are defined by the is relationship trait. It should receive (at least) a Str named parameter called :model that represents the related model, a Callable positional parameter that will return one (or more) referencing columns, and it must have a sigil. The sigil can be:

  • $ - Represents a belongs to relationship that "stores" only 1 element. Red will run the callable passing the model itself as the only parameter.

  • @ - Represents a has many relationship that "stores" a ResultSeq of elements. Red will run the callable passing the model defined by the :model named parameter.

  • $ with the :has-one option - Represents a has one relationship: the foreign key lives on the other model's table. Accessing it returns the related object (or an undefined creation context when empty — see "creating through a scalar relationship" below). On .^create, Red fills the foreign key on the related row automatically.

So, for example:

# Person.rakumod
use Red:api<2>;

model Person {
  has UInt $!id    is serial;
  has Str  $.name  is column;
  has      @.books is relationship(*.author-id, :model<Book>);
}
# Book.rakumod
use Red:api<2>;

model Book {
  has UInt $!id        is serial;
  has Str  $.name      is column;
  has UInt $!author-id is referencing(*.id, :model<Person>);
  has      $.author    is relationship(*.author-id, :model<Person>);
}

Book has a foreign key (.author) that's auto pre-fetched using a join based on book.author_id = person.id.

Person has no foreign key but it does have a relationship (@.books) that isn't pre-fetched because it's a has many relationship. So when its value is accessed a new query is run.

On that example, to create a new book related to (written by) a given person, one could do something like:

my $author = Person.^all.first: *.name eq "Chico Buarque";
$author.books.create: :name<Benjamin>;

As mentioned, @.books is a ResultSeq, so it accepts any of its methods, eg:

$author.books.grep(*.name.starts-with("Ben")).elems

For getting the number of books written by "Chico Buarque" that starts with "Ben".

has-one

A scalar relationship declared with :has-one means "the other table holds the foreign key". For example, an account has one profile, and the profile table holds the account-id:

model Profile { ... }

model Account {
    has UInt    $.id      is serial;
    has Str     $.name    is column;
    has Profile $.profile is relationship(*.account-id, :model<Profile>, :has-one);
}

model Profile {
    has UInt $.id         is serial;
    has UInt $.account-id is referencing(*.id, :model<Account>);
    has Str  $.bio        is column;
    has      $.account    is relationship(*.account-id, :model<Account>);
}

Creating through a scalar relationship

An empty scalar relationship returns an undefined, false type object carrying the relationship's creation context, rather than Nil. Call .^create on that object to create the related row and fill the foreign key automatically:

my $parent  = $child.parent.^create(:name<parent>);

# For a relationship declared with :has-one:
my $profile = $account.profile.^create(:bio<hello>);

For a belongs-to relationship, Red saves the foreign key on the existing source row. For :has-one, Red supplies the source key to the new related row. The source must already be saved. Both writes participate in one transaction; a failed operation rolls back its writes and restores the source's attribute and dirty state. Inside a transaction, the operation uses a savepoint.

Existing relationships continue to return their related instances. An empty relationship still tests false and undefined, but code that checks specifically for Nil should use .defined instead. Creation uses .^create, while plural relationships continue to use .create.

Red v0.2.17

A Raku ORM

Authors

  • Fernando Correa de Oliveira

License

Artistic-2.0

Dependencies

ConfigurationDBIishUUIDJSON::Fast

Test Dependencies

Provides

  • CX::Red::Bool
  • MetamodelX::Red::Comparate
  • MetamodelX::Red::Describable
  • MetamodelX::Red::Dirtable
  • MetamodelX::Red::GlobalNotifiable
  • MetamodelX::Red::Id
  • MetamodelX::Red::Migration
  • MetamodelX::Red::Model
  • MetamodelX::Red::OnDB
  • MetamodelX::Red::Populatable
  • MetamodelX::Red::PreFetch
  • MetamodelX::Red::Refreshable
  • MetamodelX::Red::Relationship
  • MetamodelX::Red::Specialisable
  • MetamodelX::Red::SubModelHOW
  • MetamodelX::Red::Supply
  • MetamodelX::Red::View
  • MetamodelX::Red::VirtualView
  • Red
  • Red::AST
  • Red::AST::AddForeignKeyOnTable
  • Red::AST::BeginTransaction
  • Red::AST::Between
  • Red::AST::BoundFilter
  • Red::AST::Case
  • Red::AST::Chained
  • Red::AST::ChangeColumn
  • Red::AST::Comment
  • Red::AST::CommitTransaction
  • Red::AST::Constraints
  • Red::AST::CreateColumn
  • Red::AST::CreateIndex
  • Red::AST::CreateTable
  • Red::AST::CreateView
  • Red::AST::DateTimeFuncs
  • Red::AST::Delete
  • Red::AST::Divisible
  • Red::AST::DriverExtension
  • Red::AST::DropColumn
  • Red::AST::Empty
  • Red::AST::Function
  • Red::AST::Generic::Infix
  • Red::AST::Generic::Postfix
  • Red::AST::Generic::Prefix
  • Red::AST::Infix
  • Red::AST::Infixes
  • Red::AST::Insert
  • Red::AST::Intersect
  • Red::AST::IsDefined
  • Red::AST::JsonItem
  • Red::AST::JsonOperation
  • Red::AST::JsonRemoveItem
  • Red::AST::JsonSetItem
  • Red::AST::LastInsertedRow
  • Red::AST::Minus
  • Red::AST::MultiSelect
  • Red::AST::Native
  • Red::AST::Next
  • Red::AST::Operator
  • Red::AST::Optimizer::AND
  • Red::AST::Optimizer::Case
  • Red::AST::Optimizer::OR
  • Red::AST::Ordering
  • Red::AST::ProductSource
  • Red::AST::ProjectionField
  • Red::AST::Reference
  • Red::AST::RegexCapture
  • Red::AST::RegexChars
  • Red::AST::RegexMatch
  • Red::AST::ReleaseSavepoint
  • Red::AST::RollbackToSavepoint
  • Red::AST::RollbackTransaction
  • Red::AST::RowContext
  • Red::AST::RowParameter
  • Red::AST::Savepoint
  • Red::AST::Select
  • Red::AST::StringFuncs
  • Red::AST::TableComment
  • Red::AST::Unary
  • Red::AST::Union
  • Red::AST::Update
  • Red::AST::Value
  • Red::Attr::Column
  • Red::Attr::Index
  • Red::Attr::Query
  • Red::Attr::Relationship
  • Red::Class
  • Red::Cli
  • Red::Cli::Column
  • Red::Cli::Relationship
  • Red::Cli::Table
  • Red::Column
  • Red::ColumnMethods
  • Red::Compiler::Emitter
  • Red::Compiler::RakuAST
  • Red::Compiler::Regex
  • Red::Compiler::Runtime
  • Red::Compiler::Template
  • Red::Config
  • Red::DB
  • Red::Database
  • Red::DefaultResultSeq
  • Red::Do
  • Red::Driver
  • Red::Driver::Cache
  • Red::Driver::Cache::Memory
  • Red::Driver::CacheInvalidateOnWrite
  • Red::Driver::CacheWithStrKey
  • Red::Driver::CommonSQL
  • Red::Driver::Events
  • Red::Driver::Migrations
  • Red::Driver::Mock
  • Red::Driver::SQLite
  • Red::Driver::SQLite::Regex
  • Red::Driver::SQLite::SQLiteMaster
  • Red::Driver::SQLite::SchemaReader
  • Red::Event
  • Red::Fixture
  • Red::Formatter
  • Red::Formatter::ResultSeq
  • Red::Formatter::ResultSeq::Vertical
  • Red::FromRelationship
  • Red::GlobalEvents
  • Red::HiddenFromSQLCommenting
  • Red::Index
  • Red::LockType
  • Red::Migration::Applied
  • Red::Migration::Artifact
  • Red::Migration::Bundle
  • Red::Migration::Column
  • Red::Migration::Configuration
  • Red::Migration::Data
  • Red::Migration::Dependencies
  • Red::Migration::Driver
  • Red::Migration::Environment
  • Red::Migration::File
  • Red::Migration::Import
  • Red::Migration::Logical
  • Red::Migration::Manager
  • Red::Migration::Migration
  • Red::Migration::Planner
  • Red::Migration::Resolution
  • Red::Migration::SQL
  • Red::Migration::Scripts
  • Red::Migration::Snapshot
  • Red::Migration::Storage
  • Red::Migration::Table
  • Red::Migration::Test
  • Red::Model
  • Red::Operators
  • Red::Phaser
  • Red::PrepareCode
  • Red::Projection
  • Red::QueryPlan
  • Red::QueryPlan::Cache
  • Red::Regex
  • Red::Regex::Automaton
  • Red::Regex::Unicode
  • Red::ResultAssociative
  • Red::ResultSeq
  • Red::ResultSeq::Iterator
  • Red::ResultSeq::Supply
  • Red::ResultSeqMethods
  • Red::ResultSeqSeq
  • Red::RowSecurity
  • Red::RowSecurity::Context
  • Red::RowSecurity::DDL
  • Red::RowSecurity::PostgreSQL
  • Red::RowSecurity::Statement
  • Red::RowSecurity::Write
  • Red::Runtime::Configuration
  • Red::Schema
  • Red::SchemaReader
  • Red::Statement
  • Red::Traits
  • Red::Transaction::Guard
  • Red::Type
  • Red::Type::Json
  • Red::Type::Map
  • Red::Utils
  • X::Red::Exceptions
  • X::Red::Migration

Documentation

The Camelia image is copyright 2009 by Larry Wall. "Raku" is a trademark of the Yet Another Society. All rights reserved.

Built with Podlite — the markup and publishing tools behind this site.