PHP code example of ronanchilvers / orm

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

    

ronanchilvers / orm example snippets


$pdo = new PDO('sqlite::memory:');

Ronanchilvers\Orm\Orm::setConnection($pdo);

class Book extends Model
{}

class Book extends Model
{
    static protected $columnPrefix = 'book';
}

class Book extends Model
{
    static protected $table        = 'my_books_table';
    static protected $columnPrefix = 'book';
}

$finder = Orm::finder(Book::class);

$books = $finder->all();

// Get all the records in one go
$books = $finder->all();

// Get the third page of models when there are 30 records per page
// (10 per page is the default)
$books = $finder->all(3, 30);

// Get a specific model by its primary key, here assumed to be numeric
$book = $finder->one(23);

// Get all the books for author id 20
$books = $finder->select()->where('book_author', 20);

// Get all books added since last week - here we're using the excellent Carbon wrapper
// for DateTime
$recentBooks = $finder->select()->where('book_created', '>', Carbon::now()->subWeek());

$sql = "SELECT *
FROM books
  LEFT JOIN authors ON author_id = book_author
WHERE author_name LIKE :name
  AND author_created < :created";
$params = [
  'name'    => 'Fred%',
  'created' => Carbon::now()->subYear()->format('Y-m-d H:i:s'),
];
$books = $finder->query($sql, $params);

class BookFinder extends Finder
{
    public function forAuthorId(int $id): array
    {
        return $this
          ->select()
          ->where(Book::prefix('author'), $id)
          ->execute();
    }
}

class Book extends Model
{
    static protected $finder = BookFinder::class;
}

// $finder will be an instance of BookFinder here
$finder = Orm::finder(Book::class);
$authors = $finder->forAuthorId(2);

$finder = Orm::finder(Book::class);
$book = $finder->one(23);
$book->save();

$book->delete();

$finder = Orm::finder(Book::class);
$book = $finder->one(72);
echo $book->name;