Mad::Mapper::Guides::Custom - How to do custom queries
This guide will show how to run custom queries for full control.
It is possible to override the private methods _find_sql(), _insert_sql(), _update_sql() and _delete_sql() for more control. The benefit of overriding these methods is if you want to use optional columns for doing queries. The example below can find a row based on both the "id" and "email" column.
_find_sql()
_insert_sql()
_update_sql()
_delete_sql()
sub _find_sql { my $self = shift; if ($self->email) { return $self->expand_sql("SELECT %pc FROM %t WHERE email=?"), $self->email; } else { return $self->expand_sql("SELECT %pc FROM %t WHERE id=?"), $self->id; } }
Instead of using the automatic generated methods from simple SQL statements, it is possible to do the complete query yourself. Below is an example of a completely custom _insert():
_insert()
package MyApp::Model::User; use Mad::Mapper -base; sub _insert { my ($self, $cb) = @_; Mojo::IOLoop->delay( sub { my ($delay) = @_; $self->db->query("INSERT INTO users (email) VALUES (?)", $self->email, $delay->begin); }, sub { my ($delay, $err, $res) = @_; return $self->$cb($err) if $err; $self->in_storage(1); $self->id($db->dbh->last_insert_id(undef, undef, $self->table, $self->pk)); $self->$cb(""); }, ); }
You can also override _find(), _update() and _delete().
_find()
_update()
_delete()
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.
Jan Henning Thorsen - jhthorsen@cpan.org
jhthorsen@cpan.org
To install Mad::Mapper, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Mad::Mapper
CPAN shell
perl -MCPAN -e shell install Mad::Mapper
For more information on module installation, please visit the detailed CPAN module installation guide.