Skip to content
akDeveloper edited this page Jun 13, 2012 · 1 revision

Draft API

Model

Define the class

class Post extends \Lycan\Record\Model

Define attributes

public static $columns = array('id', 'title', 'text', 'user_id', 'created_at')

Define table

public static $table='posts'

It is the plural name of the model in lower case.

if model name is MyPost then table name must be my_posts with underscore.

Define primary key

public static $primary_key='id'

Define associations

public static $belongsTo=array('user')

Code examples

<?php
// Post.php
class Post extends \Lycan\Record\Model {
public static $columns = array('id', 'title', 'text', 'user_id', 'created_at');
public static $table = 'posts';
public static $primary_key = 'id';
public static $belongsTo = array('user'); public static $hasAndBelongsToMany = array('categories');
public static $hasMany = array('comments');
}

Find posts

Post::find(); // returns Query object. no query to database yet.
Post::find()->all(); // returns Collection object and execute query to database.
// SELECT * FROM `posts`;
Post::all(); // returns Collection object and execute query to database.
// SELECT * FROM `posts`;
Post::find()
->where(array('id'=>1))
->fetch();
// SELECT * FROM `posts` WHERE id = '1';
Post::find(1)->fetch();
// SELECT * FROM `posts` WHERE id = '1';
Post::findAllById(array(1, 2, 3))->all();
// SELECT * FROM `posts` WHERE id IN ('1', '2', '3');
Post::find()
->where(array('user_id = ? AND created_at = ?', 1, date('Y-m-d H:i:s'))
->all();
// SELECT * FROM `posts` WHERE user_id = '1' AND created_at = '2012-05-25 01:12:25'

Eagger Loading

// A belongsTo (many to one) relation
$post = Post::find(1)
->includes('user')
->fetch();
// SELECT * FROM `posts` WHERE id = '1';
// If post exists then
// SELECT * FROM `users` WHERE id = <user_id from post>
$user = $post->user; // returns User object

Fetching relationship object

$post = Post::find(1)->fetch();
// SELECT * FROM `posts` WHERE id = '1';
$user = $post->user; // returns BelongsTo object
// No query to database yet
echo $user->name;
// or
echo $user->fetch()->name;
// executes query
// SELECT * FROM `users` WHERE id = <user_id from post>
// A hasMany (one to many) relation
$comments = $post->comments; // return HasMany object
$comment = $comments->find()->where(array('id'=>'12')); // returns Query object. no query to database yet
$comment->fetch();
// SELECT * FROM `comments` WHERE post_id = <id from post> AND id = '12';

Adding / appending objects to hasMany relation

 $post = Post::find(1)->fetch();
$comment = new Comment();
$post->comments[] = $comment;
// INSERT INTO `comments` (post_id) VALUES (<id from post>);