2014-11-02 16 views
0

我在選擇字段時嘗試訪問相關模型時遇到了一些問題。我的CakePHP版本是3.0beta2。選擇字段時,不會加載關聯

三個MySQL表是相關的這個問題:

users: 
`id` int(11) NOT NULL, 
`username` varchar(30) COLLATE utf8_unicode_ci NOT NULL, 
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, 
`role` varchar(20) COLLATE utf8_unicode_ci NOT NULL, 
... (more information) 

-

presets: 
`id` int(11) NOT NULL, 
`name` varchar(60) COLLATE utf8_unicode_ci NOT NULL, 
`user_id` int(11) NOT NULL, 
... (more information) 

- 如下圖所示

favorites: 
`id` int(11) NOT NULL, 
`user_id` int(11) NOT NULL, 
`preset_id` int(11) NOT NULL, 
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP 

我協會的定義:

// From FavoritesTable.php 
public function initialize(array $config) { 
    $this->belongsTo('Users'); 
    $this->belongsTo('Presets'); 
} 

// From PresetsTable.php 
public function initialize(array $config) { 
    $this->belongsTo('Users'); 
    $this->hasMany('Favorites'); 
} 

// From UsersTable.php 
public function initialize(array $config) { 
    $this->hasMany('Presets'); 
    $this->hasMany('Favorites'); 
} 

我想要實現的是:

  1. 加載所有爲當前登錄用戶
  2. 加載所有該用戶擁有
  3. 收藏夾中的用戶信息創建變換一個新的領域created字段(時間戳)轉換成日期
  4. 對於每個喜愛,加載相關的預設數據

這是我使用的代碼來做到這一點:

// From UsersController.php 
public function favorites() { 

    $userId = $this->Auth->user('id'); 

    $user = $this->Users->find('all') 
     ->where(['id' => $userId]) 
     ->contain([ 
      'Favorites' => function($q) { 
       return $q 
        ->select(['id', 'preset_id', 'user_id', 'created', 'date' => 'DATE(created)']) 
        ->order(['Favorites.created' => 'DESC']); 
      }, 
      'Favorites.Presets', 
     ]) 
     ->first(); 

    $this->set('user', $user); 
} 

的問題是:當我使用select方法如在上面的代碼中,Favorites.Presets關聯未裝載,那麼$user['favorites'][0]['preset']總是null

但是,如果我註釋掉的選擇方法(因此選擇各個領域,而不是檢索DATE(created),協會正在加載,我可以訪問預設表中的信息。

難道這是一個錯誤還是我做的什麼問題?
感謝您的幫助!

回答

1

我想你需要->autoFields(true)select()後,如果您希望選擇其他所有領域。這也許可以看作是一個錯誤,這是必需打電話,嘗試打開一票在github中。

+0

解決了它。我本人從未發現過。 謝謝! – 2014-11-02 23:06:02

+0

不是一個錯誤。按照設計,使用含有限制選擇的那些。從手冊'如果您限制了使用select()加載的字段,但也想從包含的關聯中加載字段,則可以使用autoFields()'(http://book.cakephp.org/3.0/en/ ORM /檢索數據和 - resultsets.html#通過條件對包含) – Oberst 2014-12-24 19:22:55