Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4015148
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T09:35:02+00:00 2026-05-20T09:35:02+00:00

I’m starting a cakephp app, I’ve never used it in real world so I’m

  • 0

I’m starting a cakephp app, I’ve never used it in real world so I’m a bit confused how HABTM works, even though I read the documentation I couldn’t get even the $this->User->Subscription and didn’t see any extra object dumped

What I want is to create a HATBM between users and subscriptions

so I created three tables (users,subscriptions,users_subscribers)

Then in my User.php model I did this

var $hasAndBelongsToMany =
    array(
        'Subscription' =>
            array('className'=>'Subscription',
                'joinTable' => 'users_subscribers',
                'foreignKey'             => 'user_id',
               'associationForeignKey'  => 'subscription_id',
                'unique' => true,
               )
        );

SUbscription.php

    var $hasAndBelongsToMany = array(
        'User'=>array('className'=>'User',
                    'joinTable' => 'users_subscribers',
        'foreignKey' => 'subscription_id',
        'associationForeignKey' => 'user_id',
        'unique' => true));

Even with the tags example and following it, I cannot get the relation set, I also added the line <?php echo $this->element('sql_dump'); ?> to see if its running which it isn’t…

Could anyone guide me how exactly you get HATBM to work, what else do I need to verify?

Full code:
pages_controller.php
http://sao.pastebin.com/PWQMhE2z

User model:
http://sao.pastebin.com/PWqwAj1v

Subscription model:
http://sao.pastebin.com/MfVFR4Kw

subscriptions SCHEMA:
http://sao.pastebin.com/mLRcEp1c

User SCHEMA:
http://sao.pastebin.com/UeTRHh3u

users_subscriptions SCHEMA:
http://sao.pastebin.com/4UeSDZte

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T09:35:02+00:00Added an answer on May 20, 2026 at 9:35 am

    The simplest and fastest way to get this working is by following CakePHP’s rule of configuration over customization.

    This means following the CakePHP conventions unless you have a very good reason not to.

    I’d strongly recommend starting with a basic setup that you know works, and then modifying that if you need to. Here’s a quick and easy way to get up and running.

    The Database Tables

    Start with three database tables: users, subscriptions and subscriptions_users. The schemas you already have are ok, but I’d make a couple modifications to make sure things go smoothly:

    1. Add a name or title column to the users table. Either that, or you’ll have to add the $displayField property to your User model. If you don’t do this you’ll miss out on some of the “automagic” that CakePHP provides. More info on $displayField
    2. Change the join table’s name to subscriptions_users. This is the CakePHP convention and there’s no reason not to save yourself the time and worry of following it. 🙂
    3. Use the following schema for the join table:
      CREATE TABLE subscriptions_users (
      subscription_id int(11) NOT NULL,
      user_id int(11) NOT NULL
      ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
      

    Note that there aren’t any keys defined. From the CakePHP manual: “To avoid any issues – don’t define a combined primary key for these two fields, if your application requires it you can define a unique index.”

    The Models

    Try to keep your code clean. There are a lot of sensible defaults implemented in CakePHP and there’s no point in defining them when they’re already defined.

    The following models should work for you:

    user.php

    <?php
    class User extends AppModel {
        var $hasAndBelongsToMany = array('Subscription');
    }
    ?>
    

    subscription.php

    <?php
    class User extends AppModel {
        var $hasAndBelongsToMany = array('User');
    }
    ?>
    

    Pretty simple. Just be sure your model files are named correctly: user.php and subscription.php, all lowercase.

    Also, note that you don’t have to set any of the relationship options (className, joinTable, etc.) unless they need to be something besides the default. Ninety percent of the time the defaults should serve you just fine.

    You should be up and running now. You can make sure the model objects are being loaded and are accessible in your controllers like this:

    users_controller.php

    <?php
    class UsersController extends AppController {
        var $name = 'Users';
    
        function index() {
            $this->autoRender = false;
            var_dump(is_object($this->User));
            var_dump(is_object($this->User->Subscription));
        }
    }
    ?>
    

    subscriptions_controller.php

    <?php
    class SubscriptionsController extends AppController {
        var $name = 'Subscriptions';
    
        function index() {
            $this->autoRender = false;
            var_dump(is_object($this->Subscription));
            var_dump(is_object($this->Subscription->User));
        }
    }
    ?>
    

    The output of /users and /subscriptions should both be bool(true) bool(true).

    You can see the full models by doing pr($this->User);.

    Deleting records

    If you delete a single record using, for example, $this->User->delete($user_id), all the records in the join table with that user ID will automatically be deleted as well.

    If you want to delete a single record from a HABTM join table, without deleting the records that it links to, in effect, “unjoining” the two records, you can do it through the SubscriptionsUser model. This is a model that is created on the fly whenever there’s a HABTM relationship.

    See here for an example: CakePHP hasAndBelongsToMany (HABTM) Delete Joining Record

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.