From 813ef7082d9a276dbc0aa015759e5313171c1583 Mon Sep 17 00:00:00 2001
From: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
Date: Fri, 22 Jul 2016 17:20:08 +0100
Subject: [PATCH] Bug 16965: Add Koha::Objects->search_related
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

In order to search on relations, we need this new method.

Test plan:
Confirm that the changes in Objects.t make sense and that the tests
pass.

Tested all 3 patches together, followed test plan, result OK
Signed-off-by: Marc Véron <veron@veron.ch>
Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
---
 Koha/Objects.pm               | 13 +++++++++++++
 t/db_dependent/Koha/Objects.t | 13 ++++++++++++-
 2 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/Koha/Objects.pm b/Koha/Objects.pm
index 9d4d591..2b407c6 100644
--- a/Koha/Objects.pm
+++ b/Koha/Objects.pm
@@ -130,6 +130,19 @@ sub search {
     }
 }
 
+=head3 search_related
+
+    my @objects = Koha::Objects->search_related( $rel_name, $cond?, \%attrs? );
+
+Searches the specified relationship, optionally specifying a condition and attributes for matching records.
+
+=cut
+
+sub search_related {
+    my ( $self, @params ) = @_;
+    return $self->_resultset->search_related( @params );
+}
+
 =head3 Koha::Objects->next();
 
 my $object = Koha::Objects->next();
diff --git a/t/db_dependent/Koha/Objects.t b/t/db_dependent/Koha/Objects.t
index 46348e4..dcea7e5 100644
--- a/t/db_dependent/Koha/Objects.t
+++ b/t/db_dependent/Koha/Objects.t
@@ -19,7 +19,7 @@
 
 use Modern::Perl;
 
-use Test::More tests => 7;
+use Test::More tests => 8;
 use Test::Warn;
 
 use Koha::Authority::Types;
@@ -81,5 +81,16 @@ subtest 'not_covered_yet' => sub {
     warning_is { Koha::Patrons->search->not_covered_yet } { carped => 'The method not_covered_yet is not covered by tests' }, "If a method is not covered by tests, the AUTOLOAD method won't execute the method";
 };
 
+subtest 'search_related' => sub {
+    plan tests => 3;
+    my $builder   = t::lib::TestBuilder->new;
+    my $patron_1  = $builder->build( { source => 'Borrower' } );
+    my $patron_2  = $builder->build( { source => 'Borrower' } );
+    my $libraries = Koha::Patrons->search( { -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } } )->search_related('branchcode');
+    is( $libraries->count,            2,                       'Koha::Objects->search_related should work as expected' );
+    is( $libraries->next->branchcode, $patron_1->{branchcode}, 'Koha::Objects->search_related should work as expected' );
+    is( $libraries->next->branchcode, $patron_2->{branchcode}, 'Koha::Objects->search_related should work as expected' );
+};
+
 $schema->storage->txn_rollback;
 1;
-- 
2.8.1