Example

Create

  1. $p = new Post(array(‘title’ => ‘First Post!11!’, ‘body’ => ‘This is the body of my post’));
  2. $p->save(); # saves this post to the table
  3.  
  4. $p2 = new Post();
  5. $p2->title = "Second Post";
  6. $p2->body = "This is the body of the second post";
  7. $p2->save(); # save yet another post to the db

Retrieve

  1. $p = Post::find(1); # finds the post with an id = 1
  2. $p->title; # title of this post
  3. $p->body;  # body of this post
  4.  
  5. # returns the 10 most recent posts in an array, assuming you have a column called "timestamp"
  6. $posts = Post::find(‘all’, array(‘order’ => ‘timestamp DESC’, ‘limit’ => 10));

Update

  1. $p = Post::find(1);
  2. $p->title = "Some new title";
  3. $p->save(); # saves the change to the post
  4.  
  5. # alternatively, the following is useful when a form submits an array
  6. $_POST[‘post’] = array(‘title’ => ‘New Title’, ‘body’ => ‘New body here!’);
  7. $p = Post::find(1);
  8. $p->update_attributes($_POST[‘post’]); # saves the object with these attributes updated

Destroy

  1. $p = Post::find(1);
  2. $p->destroy();

Relationships

  1. $p = Post::find(1);
  2. # call to $p->comments results in query to get all comments for this post
  3. # a subsequent call to $p->comments would not result in a query, but use results from previous query
  4. foreach ($p->comments as $comment) {
  5.   echo $comment->content;
  6. }

Related Pages

Leave a Comment