i have mysql query question.
select a.* products inner join product_tags b on a.product_id = b.product_id b.tag_id in (1,23,54) group a.product_id having count(1) = 3
i trying figure how converted dbix::class syntax?
from dbix docs, says joins, not sure how incorporate it?
defining joins , relationships ^
in dbix::class each relationship between 2 tables needs first defined in resultsource table. if relationship needs accessed in both directions (i.e. fetch tracks of cd, , fetch cd data track), needs defined both tables.
for cds/tracks example, means writing, in myschema::cd:
myschema::cd->has_many('tracks', 'myschema::tracks');
and in myschema::tracks:
myschema::tracks->belongs_to('cd', 'myschema::cd', 'cdid');
there several other types of relationships, more comprehensively described in dbix::class::relationship. using joins ^
once have defined relationships, using them in actual joins simple. type of relationship chose e.g. has_many, indicates sort of join performed. has_many produces left join example, fetch rows on left side, whether there matching rows on right (table being joined to), or not. can force other types of joins in relationship, see dbix::class::relationship docs.
when performing either search or find operation, can specify relations refine results based on, using join attribute, this:
$schema->resultset('cd')->search( { 'title' => 'funky cd', 'tracks.name' => { => 't%' } }, { join => 'tracks', order_by => ['tracks.id'], } );
if don't recognise of syntax, should go read "search" in dbix::class::resultset , "attributes" in dbix::class::resultset, here's quick break down:
the first argument search hashref of attributes, in case restriction on title column in cd table, , restriction on name of track in tracks table, tracks related chosen cd(s). second argument hashref of attributes search, results returned sorted id of related tracks.
so first you'd define rel on tags products.
myschema::result::product->has_many( 'tags', 'myschema::result::producttag', 'product_id' );
thne define rel on products tags:
myschema::result::producttag->belongs_to( 'products', 'myschema::result::product', 'product_id' );
these have been inferred if using schema::loader way. (shameless plug: above shorter , sweeter dbix::class::candy , dbix::class::helper::row::relationshipdwim)
now replicate original query:
$schema->resultset('product')->search({ tags.tag_id => { -in => [1,23,54] }, }, { join => 'tags', group_by => 'me.product_id', having => { 'count 1' => 3 }, })
Comments
Post a Comment