How do I get values ​​from a reference table in DBIx :: Class?

In my application, I have 2 tables, books and tags and a table of links book_tags. The link table also contains the number of times a book has been tagged with that particular tag. I can add a tag by doing

$book->add_tag($tag, { tag_count => 10 });

      

However, when I extract the tags for the book

@tags = $book->tags();

      

it does not return values ​​from the reference table.

Is there a way to get values ​​from the link table without doing it manually?

+2


source to share


3 answers


Since you have a named join table book_tags

, you will need to create a relationship many_to_many

from the table books

to the relationship of has_many

the table itself books

. The relationship has_many

should retrieve the id

tags associated with the book from the table book_tags

. You may need to add relationships similar to:

In Your::App::Schema::Result::Book

:

__PACKAGE__->has_many( book_tags => 'Your::App::Schema::Result::BookTag', 'book_id' );

__PACKAGE__->many_to_many( tags => 'book_tags', 'tag' );

      



In Your::App::Schema::Result::BookTag

:

__PACKAGE__->belongs_to( tag => 'Your::App::Schema::Result::Tag', 'tag_id' );

      

+2


source


You can proxy

properties through relationships like this:

Schema::Tag->has_many('book_tags' => 'Schema::BookTag',  
  undef, {  
    proxy => [ 'tag_count' ],  
  }  
);

      

Then you can access the 'tag_count' like this:



my $tag_rs = $book->tags;
for( my $tag = $tag_rs->next ){
  print $tag->tag_count;
}

      

More information can be found in the relationship docs .

+1


source


Thank! I've already done this part and it works.

My tables look like this:

BOOK:

book_id book_title [other fields]

      

TAG:

tag_id tag_name [other fields]

      

BOOK_TAG:

book_id tag_id tag_count

      

So I have a relationship between tags and books with many to many with an additional tag_count attribute that is stored in the link table.

I can add a tag to a book by doing

$book->add_to_tags($tag, { tag_count => 10 } );

      

which populates the tag_count field in the BOOK_TAG table.

But when I do

$book->tags();

      

it doesn't automatically retrieve the tag_count field from the BOOK_TAG. I can write

$tag = $schema->resultset('BookTag')->find( { book_id=>$book->book_id, tag=>$tag->tag_id });
$tag_count = $tag->tag_count();

      

I am trying to figure out if there is an easier way to get an extra attribute from a link table.

0


source







All Articles