简体   繁体   中英

join more than two tables cakephp

I am writing an app that displays housing units (they are listed by users offering them for rent). I am trying to figure out how to define my Unit model in Cakephp. I have three tables: units, complexes and users.

I know that unit $belongsTo 'User', but it also belongs to 'Complex', since every complex can have many units. Can my I write this?

<?php
  class Unit extends AppModel {
        var $name='Unit';
        var $belongsTo=array('User', 'Complex');

} ?>

I should also add that I am not sure how to define my classes for User and Complex, as a User can have many Complexes and a Complex can have many Users. If one hasMany can it also belongTo the thing that it hasMany of? Is this a HABTM? I am very confused (newbie).

Sounds like a user has many complexes and a complex belongs to many users. This is a HABTM.

A user can have many units but a unit can only have one user. This is a hasMany and a belongsTo.

Now for the relationship between units and complexes, if a complex can have many units, then that is a hasMany. I would guess that to be the case. I would also guess that a unit belongs to a complex as well as a user. This is fine. Units can belong to both users and complexes without issue or needing a HABTM.

So I hav defined your relationships for you above. It seems like you know how to define hasMany and belongsTo already, so just make sure you set up HABTM as described on this page: (keep in mind that you need an extra table in your database, and don't forget to add any db columns you need for the other relationships, either).

http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM