PHP code example of cycle / orm-promise-mapper

1. Go to this page and download the library: Download cycle/orm-promise-mapper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cycle / orm-promise-mapper example snippets


use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Relation\BelongsTo;
use Cycle\Annotated\Annotation\Relation\HasMany;
use Cycle\ORM\Reference\ReferenceInterface;

#[Entity]
class User
{
    #[Column(type: 'primary')]
    public int $id;

    #[HasMany(target: Post::class, load: 'eager')]
    public array $posts;
    
    #[HasMany(target: Tag::class, load: 'lazy')]
    public ReferenceInterface|array $tags;
}

#[Entity]
class Post
{
    // ...

    #[BelongsTo(target: User::class, load: 'lazy')]
    public ReferenceInterface|User $user;

    #[BelongsTo(target: Tag::class, load: 'eager')]
    public Tag $tag;
}

$user = $orm->getRepository('user')->findByPK(1);

// $user->posts contains an array because of eager loading
foreach ($user->posts as $post) {
    // ...
}

// $user->tags contains Cycle\ORM\Reference\Promise object because of lazy loading
$tags = $user->tags->fetch();
foreach ($tags as $post) {
    // ...
}

$post = $orm->getRepository('post')->findByPK(1);

// $post->user contains Cycle\ORM\Reference\Promise object because of lazy loading
$userId = $post->user->fetch()->id;

// $post->tag contains Tag object because of eager loading
$tagName = $post->tag->name;