Mad::Ma...HasMany(3)

πŸ“¦ version 0.09, in fedora 44

πŸ’– 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 (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 on perl v5.42.2, dated 2026-06-09 β€” go forth and has_many responsibly πŸ’–βœ¨πŸ¦‹
πŸ“¦ where this page comes from