Mad::Ma...HasMany(3)
π NAME π
Mad::Mapper::Guides::HasMany β the "has many" relationship guide, bestie. This is the one where one row is like "these are all MINE" and honestly? iconic.
β¨ OVERVIEW β¨
okay so this guide is gonna walk you through how to define and use a "has many" relationship. no cap, it's easier than it sounds.
π¦ GUIDE π¦
πΈ Define a relationship πΈ
package MyApp::Model::User;
use Mad::Mapper -base;
# define a primary key
pk id => undef;
# define a relationship
has_many groups => "MyApp::Model::Group", "id_user";
so what is this code even saying? bestie, it's saying that the "id_user" column over in the "groups" table should reference back to the "id" (that's the primary key, the main character) column in the "users" table. it's giving "these groups belong to this user, periodt." π
π Automatically defined methods π
the "groups" relationship you just defined up there? it's gonna generate two methods for you, no extra work required:
groups()add_group()
the first one is for getting all the group rows. the second one is for adding a new group row. two little gifts, you're welcome. π«Ά
π Usage π
my $user = MyApp::Model::User->new(db => $pg->db, id => 42);
first things first: you gotta create a $user object. after that we can retrieve groups and/or add groups. slay.
# sync
my $groups = $user->groups;
# async
Mojo::IOLoop->delay(
sub {
my ($delay) = @_;
$self->groups($delay->begin);
},
sub {
my ($delay, $err, $groups) = @_;
},
);
heads up: $groups is a Mojo::Collection of "MyApp::Model::Group" objects. a whole little squad of them. π
# add_group() is a sync method
$group = $self->add_group(\%constructor_args);
# save() can be called sync and async.
$group->save;
ngl this next part matters: "add_group" will just create a new "MyApp::Model::Group" object. that's it. you need to insert that object as a separate step β it does not do that for you, bestie. π
π« Custom query π«
you can define your own query too, if you're feeling fancy:
has_many groups_sorted => "MyApp::Model::Group";
sub _has_many_groups_sorted_sql {
my ($self, $related_class, @extra) = @_;
return $related_class->expand_sql(
"SELECT %pc FROM %t WHERE user_id=? order by name", $self->id
);
}
note above that @extra is any extra arguments passed on to the method, like so:
$user->groups_sorted("extra", "args");
iykyk. β¨
π COPYRIGHT AND LICENSE π
Copyright (C) 2014-2016, Jan Henning Thorsen
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.
β AUTHOR β
Jan Henning Thorsen - "jhthorsen@cpan.org"
and that's the whole vibe, bestie π this page was living its best life onperl v5.42.2, dated2026-06-09β go forth and has_many responsibly πβ¨π¦
π¦ where this page comes from
- fedora 44: perl-Mad-Mapper 0.09-2.fc44 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms