Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I create a nested has_many or belongs_to relationship with DBIx::Class?
    text
    copied!<p>In my code I have three classes as follows: <code>Forum</code>, <code>Forum::Thread</code> and <code>Forum::Post</code></p> <p>What I want to do is create a belongs_to-relationship from the <code>Forum::Post</code> class to the <code>Forum</code> class and vice versa with a has_many, <em>preferably</em> without creating a custom function for it. (This is admittedly more of an intellectual exercise than a technical limitation or actual problem, but if it is possible, I would much like to know.)</p> <p>The commented out lines contain my intention with the relationships, but in their current form, they fail to work. I've poked around in the documentation, but cannot find anything relevant to this specific case.</p> <p>Any pointers?</p> <p>The forum class:</p> <pre><code>package Schema::Result::Forum; use Moose; extends qw/DBIx::Class/; __PACKAGE__-&gt;load_components (qw/Core/); __PACKAGE__-&gt;table ('forum'); __PACKAGE__-&gt;add_columns ( id =&gt; { is_auto_increment =&gt; 1, data_type =&gt; 'integer', }, ); __PACKAGE__-&gt;set_primary_key ('id'); __PACKAGE__-&gt;has_many (threads =&gt; 'Schema::Result::Forum::Thread'); #This is the interesting line #__PACKAGE__-&gt;has_many (posts =&gt; 'threads' =&gt; 'forums' ); 1; </code></pre> <p>The thread class:</p> <pre><code>package Schema::Result::Forum::Thread; use Moose; extends qw/DBIx::Class/; __PACKAGE__-&gt;load_components (qw/Core/); __PACKAGE__-&gt;table ('forum_thread'); __PACKAGE__-&gt;add_columns ( id =&gt; { is_auto_increment =&gt; 1, data_type =&gt; 'integer', }, forum =&gt; { data_type =&gt; 'integer', }, ); __PACKAGE__-&gt;set_primary_key ('id'); __PACKAGE__-&gt;belongs_to (forum =&gt; 'Schema::Result::Forum'); __PACKAGE__-&gt;has_many (posts =&gt; 'Schema::Result::Forum::Post'); 1; </code></pre> <p>The post class:</p> <pre><code>package Schema::Result::Forum::Post; use Moose; extends qw/DBIx::Class/; __PACKAGE__-&gt;load_components (qw/Core/); __PACKAGE__-&gt;table ('forum_post'); __PACKAGE__-&gt;add_columns ( id =&gt; { is_auto_increment =&gt; 1, data_type =&gt; 'integer', }, thread =&gt; { data_type =&gt; 'integer', }, ); __PACKAGE__-&gt;set_primary_key ('id'); __PACKAGE__-&gt;belongs_to (thread =&gt; 'Schema::Result::Forum::Thread'); #This is the other interesting line #__PACKAGE__-&gt;belongs_to (forum =&gt; 'thread' =&gt; 'forum'); 1; </code></pre> <p><strong>PS:</strong> Additional columns to hold actual content were omitted for brevity.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload