Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Association in cakephp

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 215
    Comment on it

    Association is basically linking two models of the database.

    It is very useful.

    After applying association you don't need to join the tables from the controller and fetch the data of another model from the controller.

    The four types of association are-

    1. hasOne- It's one to one association. Like a user has only one profile. each user entry will point towards one profile entry.

    2.hasMany- It's one to many association. Like a user has many departments. each user will point toward many departments.

    3. belongsTo- It's many to one association. Like multiple users can have a single office building. Multiple user will point towards a single office building.

    4. hasAndBelongsToMany - It's many to many association. Like multiple users have multiple departments. many users will point toward many departments.

    You can simply use them in your model where  you want to apply association.

    Like if you want to join user with department and department with user.

    You can go to user model and define.

    class User extends AppModel {
    $hasMany = ("departments");

    or if you want to give some more functionalities you can use array.

    class User extends AppModel {
    $hasMany = array("departments", array("
    
    'conditions' => array('Department.store' => '1'),
                'order' => 'Department.created DESC'));
    This makes the fetching of data really easy from one controller only.

    But in case you want to find the data of only the user you have to use recursive -1 in your controller so it can fetch the data of that particular model only.

     

     

 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: