Relationship documentation on extended (custom) relationship conditions
Jess Robinson [Sat, 4 Sep 2010 17:40:18 +0000 (18:40 +0100)]
lib/DBIx/Class/Relationship.pm
lib/DBIx/Class/Relationship/Base.pm

index d4926d1..ff26676 100644 (file)
@@ -105,20 +105,23 @@ L<DBIx::Class::Relationship::Base>.
 
 All helper methods are called similar to the following template:
 
-  __PACKAGE__->$method_name('relname', 'Foreign::Class', \%cond | \@cond, \%attrs);
+  __PACKAGE__->$method_name('relname', 'Foreign::Class', 
+                            \%cond | \@cond | \&conf, \%attrs);
 
-Both C<$cond> and C<$attrs> are optional. Pass C<undef> for C<$cond> if
-you want to use the default value for it, but still want to set C<\%attrs>.
+Both C<cond> and C<attrs> are optional. Pass C<undef> for C<cond> if
+you want to use the default value for it, but still want to set C<attrs>.
 
-See L<DBIx::Class::Relationship::Base> for documentation on the
-attributes that are allowed in the C<\%attrs> argument.
+See L<DBIx::Class::Relationship::Base/condition> for full documentation on definition of the C<cond> argument.
+
+See L<DBIx::Class::Relationship::Base/attributes> for documentation on the
+attributes that are allowed in the C<attrs> argument.
 
 
 =head2 belongs_to
 
 =over 4
 
-=item Arguments: $accessor_name, $related_class, $our_fk_column|\%cond|\@cond?, \%attrs?
+=item Arguments: $accessor_name, $related_class, $our_fk_column|\%cond|\@cond|\$cond?, \%attrs?
 
 =back
 
@@ -127,7 +130,7 @@ class's primary key in one (or more) of the calling class columns.
 This relationship defaults to using C<$accessor_name> as the column
 name in this class to resolve the join against the primary key from
 C<$related_class>, unless C<$our_fk_column> specifies the foreign key column
-in this class or C<cond> specifies a reference to a join condition hash.
+in this class or C<cond> specifies a reference to a join condition.
 
 =over
 
@@ -155,13 +158,11 @@ OR
 
 =item cond
 
-A hashref where the keys are C<foreign.$column_on_related_table> and
-the values are C<self.$our_fk_column>. This is useful for
-relations that are across multiple columns.
+A hashref, arrayref or coderef specifying a custom join expression. For
+documentation see L<DBIx::Class::Relationship/condition>.
 
 =back
 
-
   # in a Book class (where Author has many Books)
   My::DBIC::Schema::Book->belongs_to( 
     author => 
@@ -191,12 +192,14 @@ relations that are across multiple columns.
   $book->get_column('author_id');
 
 
-If the relationship is optional -- i.e. the column containing the foreign key
-can be NULL -- then the belongs_to relationship does the right thing. Thus, in
-the example above C<$obj-E<gt>author> would return C<undef>.  However in this
-case you would probably want to set the C<join_type> attribute so that a C<LEFT
-JOIN> is done, which makes complex resultsets involving C<join> or C<prefetch>
-operations work correctly.  The modified declaration is shown below:
+If the relationship is optional -- i.e. the column containing the
+foreign key can be NULL -- then the belongs_to relationship does the
+right thing. Thus, in the example above C<< $obj->author >> would
+return C<undef>.  However in this case you would probably want to set
+the L<join_type|DBIx::Class::Relationship/join_type> attribute so that
+a C<LEFT JOIN> is done, which makes complex resultsets involving
+C<join> or C<prefetch> operations work correctly.  The modified
+declaration is shown below:
 
   # in a Book class (where Author has_many Books)
   __PACKAGE__->belongs_to(
@@ -213,13 +216,13 @@ in the $attr hashref.
 
 By default, DBIC will return undef and avoid querying the database if a
 C<belongs_to> accessor is called when any part of the foreign key IS NULL. To
-disable this behavior, pass C<< undef_on_null_fk => 0 >> in the C<$attr>
+disable this behavior, pass C<< undef_on_null_fk => 0 >> in the C<\%attrs>
 hashref.
 
 NOTE: If you are used to L<Class::DBI> relationships, this is the equivalent
 of C<has_a>.
 
-See L<DBIx::Class::Relationship::Base> for documentation on relationship
+See L<DBIx::Class::Relationship::Base/attributes> for documentation on relationship
 methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
 for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
 which can be assigned to relationships as well.
@@ -228,7 +231,7 @@ which can be assigned to relationships as well.
 
 =over 4
 
-=item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond?, \%attrs?
+=item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond\&cond?, \%attrs?
 
 =back
 
@@ -238,7 +241,7 @@ records in the foreign table (e.g. a C<LEFT JOIN>). This relationship
 defaults to using the end of this classes namespace as the foreign key
 in C<$related_class> to resolve the join, unless C<$their_fk_column>
 specifies the foreign key column in C<$related_class> or C<cond>
-specifies a reference to a join condition hash.
+specifies a reference to a join condition.
 
 =over
 
@@ -267,19 +270,8 @@ OR
 
 =item cond
 
-A hashref where the keys are C<foreign.$their_fk_column> and
-the values are C<self.$matching_column>. This is useful for
-relations that are across multiple columns.
-
-OR
-
-An arrayref containing an SQL::Abstract-like condition. For example a
-link table where two columns link back to the same table. This is an
-OR condition.
-
-  My::Schema::Item->has_many('rels', 'My::Schema::Relationships',
-                             [ { 'foreign.LItemID' => 'self.ID' },
-                               { 'foreign.RItemID' => 'self.ID'} ]);
+A hashref, arrayref  or coderef specifying a custom join expression. For
+documentation see L<DBIx::Class::Relationship/condition>.
 
 =back
 
@@ -329,13 +321,14 @@ OR condition.
   $author->add_to_books(\%col_data);
 
 
-Three methods are created when you create a has_many relationship.  The first
-method is the expected accessor method, C<$accessor_name()>.  The second is
-almost exactly the same as the accessor method but "_rs" is added to the end of
-the method name.  This method works just like the normal accessor, except that
-it always returns a resultset, even in list context. The third method,
-named C<< add_to_$relname >>, will also be added to your Row items; this
-allows you to insert new related items, using the same mechanism as in
+Three methods are created when you create a has_many relationship.
+The first method is the expected accessor method, C<$accessor_name()>.
+The second is almost exactly the same as the accessor method but "_rs"
+is added to the end of the method name, eg C<$accessor_name_rs()>.
+This method works just like the normal accessor, except that it always
+returns a resultset, even in list context. The third method, named C<<
+add_to_$relname >>, will also be added to your Row items; this allows
+you to insert new related items, using the same mechanism as in
 L<DBIx::Class::Relationship::Base/"create_related">.
 
 If you delete an object in a class with a C<has_many> relationship, all
@@ -352,16 +345,17 @@ the related objects will be copied as well. To turn this behaviour off,
 pass C<< cascade_copy => 0 >> in the C<$attr> hashref. The behaviour
 defaults to C<< cascade_copy => 1 >>.
 
-See L<DBIx::Class::Relationship::Base> for documentation on relationship
-methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
-for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
-which can be assigned to relationships as well.
+See L<DBIx::Class::Relationship::Base/attributes> for documentation on
+relationship methods and valid relationship attributes. Also see
+L<DBIx::Class::ResultSet> for a L<list of standard resultset
+attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
+relationships as well.
 
 =head2 might_have
 
 =over 4
 
-=item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond?, \%attrs?
+=item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, \%attrs?
 
 =back
 
@@ -369,7 +363,7 @@ Creates an optional one-to-one relationship with a class. This relationship
 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
 resolve the join, unless C<$their_fk_column> specifies the foreign key
 column in C<$related_class> or C<cond> specifies a reference to a join
-condition hash.
+condition.
 
 =over
 
@@ -397,9 +391,8 @@ OR
 
 =item cond
 
-A hashref where the keys are C<foreign.$their_fk_column> and
-the values are C<self.$matching_column>. This is useful for
-relations that are across multiple columns.
+A hashref, arrayref  or coderef specifying a custom join expression. For
+documentation see L<DBIx::Class::Relationship/condition>.
 
 =back
 
@@ -436,27 +429,28 @@ update, so if your database has a constraint on the relationship, it
 will have deleted/updated the related records or raised an exception
 before DBIx::Class gets to perform the cascaded operation.
 
-See L<DBIx::Class::Relationship::Base> for documentation on relationship
-methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
-for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
-which can be assigned to relationships as well.
+See L<DBIx::Class::Relationship::Base/attributes> for documentation on
+relationship methods and valid relationship attributes. Also see
+L<DBIx::Class::ResultSet> for a L<list of standard resultset
+attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
+relationships as well.
 
-Note that if you supply a condition on which to join, if the column in the
+Note that if you supply a condition on which to join, and the column in the
 current table allows nulls (i.e., has the C<is_nullable> attribute set to a
 true value), than C<might_have> will warn about this because it's naughty and
-you shouldn't do that.  
+you shouldn't do that. The warning will look something like:
 
- "might_have/has_one" must not be on columns with is_nullable set to true (MySchema::SomeClass/key)
+   "might_have/has_one" must not be on columns with is_nullable set to true (MySchema::SomeClass/key)
 
 If you must be naughty, you can suppress the warning by setting
 C<DBIC_DONT_VALIDATE_RELS> environment variable to a true value.  Otherwise,
-you probably just want to use C<DBIx::Class::Relationship/belongs_to>.
+you probably just meant to use C<DBIx::Class::Relationship/belongs_to>.
 
 =head2 has_one
 
 =over 4
 
-=item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond?, \%attrs?
+=item Arguments: $accessor_name, $related_class, $their_fk_column|\%cond|\@cond|\&cond?, \%attrs?
 
 =back
 
@@ -464,7 +458,7 @@ Creates a one-to-one relationship with a class. This relationship
 defaults to using C<$accessor_name> as the foreign key in C<$related_class> to
 resolve the join, unless C<$their_fk_column> specifies the foreign key
 column in C<$related_class> or C<cond> specifies a reference to a join
-condition hash.
+condition.
 
 =over
 
@@ -492,9 +486,8 @@ OR
 
 =item cond
 
-A hashref where the keys are C<foreign.$their_fk_column> and
-the values are C<self.$matching_column>. This is useful for
-relations that are across multiple columns.
+A hashref, arrayref  or coderef specifying a custom join expression. For
+documentation see L<DBIx::Class::Relationship/condition>.
 
 =back
 
@@ -527,17 +520,19 @@ always present. The only difference between C<has_one> and
 C<might_have> is that C<has_one> uses an (ordinary) inner join,
 whereas C<might_have> defaults to a left join.
 
-The has_one relationship should be used when a row in the table has exactly one
-related row in another table. If the related row might not exist in the foreign
-table, use the L<DBIx::Class::Relationship/might_have> relationship.
+The has_one relationship should be used when a row in the table must
+have exactly one related row in another table. If the related row
+might not exist in the foreign table, use the
+L<DBIx::Class::Relationship/might_have> relationship.
 
 In the above example, each Book in the database is associated with exactly one
 ISBN object.
 
-See L<DBIx::Class::Relationship::Base> for documentation on relationship
-methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
-for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
-which can be assigned to relationships as well.
+See L<DBIx::Class::Relationship::Base/attributes> for documentation on
+relationship methods and valid relationship attributes. Also see
+L<DBIx::Class::ResultSet> for a L<list of standard resultset
+attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
+relationships as well.
 
 Note that if you supply a condition on which to join, if the column in the
 current table allows nulls (i.e., has the C<is_nullable> attribute set to a
@@ -628,10 +623,11 @@ set: C<roles>, C<add_to_roles>, C<set_roles>, and similarly named accessors
 will be created for the Role class for the C<actors> many_to_many
 relationship.
 
-See L<DBIx::Class::Relationship::Base> for documentation on relationship
-methods and valid relationship attributes. Also see L<DBIx::Class::ResultSet>
-for a L<list of standard resultset attributes|DBIx::Class::ResultSet/ATTRIBUTES>
-which can be assigned to relationships as well.
+See L<DBIx::Class::Relationship::Base/attributes> for documentation on
+relationship methods and valid relationship attributes. Also see
+L<DBIx::Class::ResultSet> for a L<list of standard resultset
+attributes|DBIx::Class::ResultSet/ATTRIBUTES> which can be assigned to
+relationships as well.
 
 =cut
 
index 71554c7..44496c4 100644 (file)
@@ -15,6 +15,17 @@ DBIx::Class::Relationship::Base - Inter-table relationships
 
 =head1 SYNOPSIS
 
+    __PACKAGE__->add_relationship('spiders',
+                                  'My::DB::Result::Creatures',
+                                  sub {
+                                    my ( $me_alias, $rel_alias) = @_;
+                                    return
+                                       { "${rel_alias}.id"    => { '=' => \"${me_alias}.id"},
+                                         "${rel_alias}.type"  => { '=', "arachnid" },
+                                        };
+                                     
+                                  });
+
 =head1 DESCRIPTION
 
 This class provides methods to describe the relationships between the
@@ -27,50 +38,146 @@ methods, for predefined ones, look in L<DBIx::Class::Relationship>.
 
 =over 4
 
-=item Arguments: 'relname', 'Foreign::Class', $cond, $attrs
+=item Arguments: 'relname', 'Foreign::Class', $condition, $attrs
 
 =back
 
-  __PACKAGE__->add_relationship('relname', 'Foreign::Class', $cond, $attrs);
+  __PACKAGE__->add_relationship('relname', 
+                                'Foreign::Class', 
+                                $condition, $attrs);
+
+Create a custom relationship between one result source and another
+source, indicated by its class name.
 
 =head3 condition
 
-The condition needs to be an L<SQL::Abstract>-style representation of the
-join between the tables. When resolving the condition for use in a C<JOIN>,
-keys using the pseudo-table C<foreign> are resolved to mean "the Table on the
-other side of the relationship", and values using the pseudo-table C<self>
-are resolved to mean "the Table this class is representing". Other
-restrictions, such as by value, sub-select and other tables, may also be
-used. Please check your database for C<JOIN> parameter support.
+The condition argument describes the JOIN expression used to connect
+the two sources when creating SQL queries.
 
-For example, if you're creating a relationship from C<Author> to C<Book>, where
-the C<Book> table has a column C<author_id> containing the ID of the C<Author>
-row:
+To create simple equality joins, supply a hashref containing the
+remote table column name as the key(s), and the local table column
+name as the value(s), for example:
 
   { 'foreign.author_id' => 'self.id' }
 
-will result in the C<JOIN> clause
+will result in the C<JOIN> clause:
 
   author me JOIN book book ON book.author_id = me.id
 
-For multi-column foreign keys, you will need to specify a C<foreign>-to-C<self>
-mapping for each column in the key. For example, if you're creating a
-relationship from C<Book> to C<Edition>, where the C<Edition> table refers to a
-publisher and a type (e.g. "paperback"):
+This describes a relationship between the C<Author> table and the
+C<Book> table where the C<Book> table has a column C<author_id>
+containing the ID value of the C<Author>.
+
+C<foreign> and C<self> are psuedo aliases and must be entered
+literally. They will be replaced with the actual correct table alias
+when the SQL is produced.
+
+Similarly:
 
   {
     'foreign.publisher_id' => 'self.publisher_id',
     'foreign.type_id'      => 'self.type_id',
   }
 
-This will result in the C<JOIN> clause:
+will result in the C<JOIN> clause:
 
   book me JOIN edition edition ON edition.publisher_id = me.publisher_id
     AND edition.type_id = me.type_id
 
-Each key-value pair provided in a hashref will be used as C<AND>ed conditions.
-To add an C<OR>ed condition, use an arrayref of hashrefs. See the
-L<SQL::Abstract> documentation for more details.
+This describes the relationship from C<Book> to C<Edition>, where the
+C<Edition> table refers to a publisher and a type (e.g. "paperback"):
+
+As is the default in L<SQL::Abstract>, the key-value pairs will be
+C<AND>ed in the result. C<OR> can be achieved with an arrayref, for
+example:
+
+  [
+    { 'foreign.left_itemid' => 'self.id' },
+    { 'foreign.right_itemid' => 'self.id' },
+  ]
+
+which results in the C<JOIN> clause:
+
+  items me JOIN related_items rel_link ON rel_link.left_itemid = me.id
+    OR rel_link.right_itemid = me.id
+
+This describes the relationship from C<Items> to C<RelatedItems>,
+where C<RelatedItems> is a many-to-many linking table, linking Items
+back to themselves.
+
+To create joins which describe more than a simple equality of column
+values, the custom join condition coderef syntax can be used:
+
+    sub {
+      my ( $me_alias, $rel_alias ) = @_;
+      return
+        ({ "${rel_alias}.artist"  => { '=' => \"${me_alias}.artistid"},
+           "${rel_alias}.year"    => { '>', "1979",
+                                       '<', "1990" }
+         });
+  }
+
+this will result in the C<JOIN> clause:
+
+  artist me LEFT JOIN cd cds_80s_noopt ON 
+   ( cds_80s_noopt.artist = me.artistid 
+     AND ( cds_80s_noopt.year < ? AND cds_80s_noopt.year > ? )
+   )
+
+with the bind values:
+
+   '1990', '1979'
+
+C<$rel_alias> is the equivalent to C<foreign> in the simple syntax,
+and will be replaced by the actual remote table alias in the produced
+SQL. Similarly, C<$me_alias> is the equivalent to C<self> and will be
+replaced with the local table alias in the SQL.
+
+The actual syntax returned by the coderef should be valid
+L<SQL::Abstract> syntax, similar to normal
+L<DBIx::Class::ResultSet/search> conditions.
+
+To help optimise the SQL produced, a second optional hashref can be
+returned to be used when the relationship accessor is called directly
+on a Row object:
+
+    sub {
+      my ( $me_alias, $rel_alias, $me_result_source, 
+           $rel_name, $optional_me_object ) = @_;
+      return
+        ({ "${rel_alias}.artist"  => { '=' => \"${me_alias}.artistid"},
+           "${rel_alias}.year"    => { '>', "1979",
+                                       '<', "1990" }
+         },
+         $optional_me_object &&
+         { "${rel_alias}.artist" => $optional_me_object->artistid,
+           "${rel_alias}.year"   => { '>', "1979",
+                                      '<', "1990" }
+       });
+  }
+
+Now this code:
+
+    my $artist = $schema->resultset("Artist")->find({ id => 4 });
+    $artist->cds_80s->all;
+
+Produces:
+
+    SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track
+      FROM cd me 
+      WHERE ( ( me.artist = ? AND ( me.year < ? AND me.year > ? ) ) )
+
+With the bind values:
+
+    '4', '1990', '1979'
+
+The C<$optional_me_object> used to create the second hashref contains
+a row object, the object that the relation accessor was called on.
+
+C<$me_result_source> the L<DBIx::Class::ResultSource> of the table
+being searched on, and C<$rel_name>, the name of the relation
+containing this condition, are also provided as arguments. These may
+be useful to more complicated condition calculation.
 
 =head3 attributes