2013-01-10 168 views
1

數據我有相互關聯的2種型號。CakePHP的無關聯模型

class AccountModel extends AppModel { 

    public $name = 'Account'; 
    public $belongsTo = array(
     'User' => array(
      'className' => 'User', 
      'foreignKey' => 'user_id', 

     ), 
    ); 
} 

class UserModel extends AppModel { 

    public $name = 'User'; 
    public $hasMany = array(
     'Account' => array(
      'className' => 'Account', 
      'foreignKey' => 'user_id', 

     ), 
    ); 

} 

表: 佔 -id -user_id - 其他領域......

用戶 -id - 其他領域......

從一個模型只返回請求數據這個數據,但沒有相關數據。 我想請求模型用的用戶ID和返回所有用戶的數據和相關的帳戶數據。 同樣與請求帳戶模型與一個PARAM,不ACCOUNT_ID或USER_ID,並返回所有帳戶數據和相關的用戶數據。

$User = $this->Account->findByField($param); 

只返回陣列( '帳戶'=>數組(...))和

$User = $this->User->findById($id); 

只返回陣列( '用戶'=>數組(...)),但沒有請求返回陣列( '用戶'=>陣列(...), '帳戶'=>陣列(..))

我將如何得到所有相關的數據?

問候 米。

+0

檢查http://stackoverflow.com/questions/7846230/binding-multiple-models-cakephp/7846332#7846332 – Rikesh

+0

$ this-> Account-> recursive = 2;沒有效果,與$ this-> Account-> find('first',array('conditions'=> array('field'=> $ param),'recursive'=> 2)); –

+0

轉到[這裏](http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Models.html)並搜索'saveAll($ data)'。這是關於**爲了保存記錄及其相關記錄**,這正是你想要的。祝你好運! –

回答

0

FindBy{fieldname}不允許遞歸選項(在cakephp文檔findBy<fieldName>(string $value[, mixed $fields[, mixed $order]]);中定義)。

爲了通過關係拿到遞歸數據,你應該使用find方法。

$userData = $this->User->find('first', array(
    'conditions' => array('id' => $userId), 
    'recursive' => 1, 
)); 

如果沒有返回數據,檢查以下內容: - 有沒有被傳遞一個有效的用戶ID? - 對於給定的userId,兩個表中都有數據嗎? - 您試圖運行查詢查詢時,模型是否正確加載?