Guest User

Untitled

a guest
Jan 20th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. <?php
  2. class Post extends Model {
  3. public function user() {
  4. return $this->belongs_to('User');
  5. }
  6. }
  7.  
  8. class User extends Model {
  9. public function posts() {
  10. return $this->has_many('Post'); // Note we use the model name literally - not a pluralised version
  11. }
  12. }
  13.  
  14. // Select a particular user from the database
  15. $user = Model::factory('User')->find_one($user_id);
  16. // Find the posts associated with the user
  17. $posts = $user->posts()->find_many();
  18.  
  19. // Select a particular post from the database
  20. $post = Model::factory('Post')->find_one($post_id);
  21. // Find the user associated with the post
  22. $user = $post->user()->find_one();
  23.  
  24. $posts = Model::factory('Post')->find_many();
  25. foreach ($posts as $post) {
  26. echo($post->user()->find_one()->username); // generates a query each iteration
  27. }
Add Comment
Please, Sign In to add comment