Skip to content

Another working relationship sample

Fernando Correa de Oliveira edited this page Sep 26, 2018 · 11 revisions
use lib "lib";
use Red;

model Person {...}

model Post {
    has Int     $.id        is id;
    has Int     $!author-id is referencing{ Person.id };
    has Str     $.title     is column{ :unique };
    has Str     $.body      is column;
    has Person  $.author    is relationship{ .author-id };
    has Bool    $.deleted   is column = False;
    method delete { $!deleted = True; self.^save }
}

model Person {
    has Int  $.id            is id;
    has Str  $.name          is column;
    has Post @.posts         is relationship{ .author-id };
    method active-posts { @!posts.grep: not *.deleted }
}

my $*RED-DEBUG = True;
my $*RED-DB = database "SQLite";

Person.^create-table;
Post.^create-table;

my $p  = Person.^create: :1id, :name<Fernando>;

my $post = $p.posts.create: :1id, :title<Bla>, :body<BlaBle1>;

$p.posts.create: :2id, :title<Ble>, :body<BlaBle2>;

say $p.posts.map: *.title;

$post.delete;

say $p.active-posts.map: *.id;

Output

SQL : CREATE TABLE person(
   id integer NOT NULL primary key,
   name varchar(255) NULL
)
SQL : CREATE TABLE post(
   deleted boolean NULL,
   title varchar(255) NULL,
   author_id integer NULL,
   body varchar(255) NULL,
   id integer NOT NULL primary key
)
SQL : INSERT INTO person(
   name,
   id
)
VALUES(
   'Fernando',
   1
)
SQL : INSERT INTO post(
   id,
   title,
   body,
   deleted,
   author_id
)
VALUES(
   1,
   'Bla',
   'BlaBle1',
   False,
   1
)
SQL : INSERT INTO post(
   id,
   title,
   body,
   author_id,
   deleted
)
VALUES(
   2,
   'Ble',
   'BlaBle2',
   1,
   False
)
SQL : SELECT
   title as "data"
FROM
   post
WHERE
   author_id = 1
(Bla Ble)
SQL : UPDATE post SET
   deleted = True
WHERE id = 1
SQL : SELECT
   id as "data"
FROM
   post
WHERE
   author_id = 1 AND not deleted
(2)
Clone this wiki locally