Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Recursive In CakePHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 197
    Comment on it

    Hello Readers

    By default cakephp will get the data of the Model that you are querying for and the data of the Models that are linked to the main Model.

    So, by using recursive in cakephp you will get the data of the single association as well as deeper association.

    Basically, Recursive defines the large amount of data that will be fetched from the database. So, by setting recursive(0,-1,1,2), you are fetching the amount of data from database, it can be more or less depending on how much deep are the association between Models.

    We use Recursive like that:

    -1 CakePHP fetches Group data only, no joins.
    0 CakePHP fetches Group data and its domain.
    1 CakePHP fetches a Group, its domain and its associated Users.
    2 CakePHP fetches a Group, its domain, its associated Users, and the Users associated Articles.
    

    Also note that the default recursive level is 1.

    So, we take the example of Authors, Books and Readers.

    This is the Author Model which gets the Authors data only.

     $authors = $this->Author->find('all');
        print_r($authors);
    

    Here, we set recursive = 1 get the data Author and its books.

    $this->Author->recursive = 1; 
    $authors = $this->Author->find('all');
    print_r($authors);
    

    Here, we set the recursive = 2 get the data Author, Books and its associated readers.

    $this->Author->recursive = 2; $authors = $this->Author->find('all'); print_r($authors);

    We take the Example of Author model and Book model

    An Author has many books and a book belongs to an Author

    Author Model File

    <?php
    class Author extends AppModel
    {
       var $name = 'Author';
       var $hasMany = 'Book';
    }
    ?>
    

    Book Model file

    <?php
    class Book extends AppModel
    {    var $name = 'Book';
         var $belongsTo ='Author';
    }
    ?>
    

    Now again, we are assuming that there is another association between Book Model and Reader Model

    Reader Model file

    <?php
    class Reader extends AppModel
    {    var $name = 'Reader';
         var $belongsTo ='Book';
    }
    ?>
    

    Book model file

    <?php
    class Book extends AppModel
    {    var $name = 'Book';
         var $belongsTo ='Author';
         var $hasMany ='Reader';
    }
    ?>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: