PHP code example of quillstack / orm

1. Go to this page and download the library: Download quillstack/orm 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/ */

    

quillstack / orm example snippets


use Quillstack\Orm\Attributes\{Table, Id, Column, HasMany, HasOne};
use Quillstack\Orm\{Related, Reference};

#[Table('users')]
final class User
{
    /**
     * @param Related<Post> $posts
     * @param Reference<Profile> $profile
     */
    public function __construct(
        #[Id] public ?int $id = null,
        #[Column] public string $email = '',
        #[Column] public bool $active = true,
        #[HasMany(Post::class, 'user_id')] public readonly Related $posts = new Related(),
        #[HasOne(Profile::class, 'user_id')] public readonly Reference $profile = new Reference(),
    ) {
    }
}

$orm = new Orm($connection);
$users = $orm->repository(User::class);

$users->find(7);
$users->findMany([1, 2, 3]);        // one query, not three
$users->all();
$users->get($users->query()->where('active', '=', true)->orderBy('email'));

foreach ($orm->repository(User::class)->all() as $user) {
    foreach ($user->posts as $post) {
        foreach ($post->comments as $comment) {
            echo $comment->body;
        }
    }
}

#[BelongsToMany(Tag::class, table: 'post_tag', foreignKey: 'post_id', relatedKey: 'tag_id')]
public readonly Related $tags = new Related();

$user->posts->all();          // Post[]
$user->posts->first();
$user->posts->count();
$user->posts->isEmpty();
foreach ($user->posts as $post) { … }

$post->user->get();           // ?User
$post->user->isPresent();

$user = $users->save(new User(email: '[email protected]'));   // inserted, and given its id
$user->email = '[email protected]';
$users->save($user);                                        // updated
$users->delete($user);

foreach ($rows as $row) {
    $orm->persist(new User(email: $row['email']));
}

$orm->flush();

$users->get($users->whereHas('posts'));
$users->get($users->whereHas('posts', fn (Query $q) => $q->where('title', 'LIKE', '%php%')));
$users->get($users->whereDoesntHave('posts'));

$page = $users->page($users->whereHas('posts')->orderBy('email'), page: 2, perPage: 20);

$page->items;      // User[]
$page->total;      // how many there are altogether
$page->pages();
$page->hasMore();
foreach ($page as $user) { … }

$migrator = new Migrator($connection);

$plan = $migrator->plan([User::class, Post::class, Comment::class, Profile::class]);
$migrator->apply($plan);