2012-04-09 27 views
0

我已經構建了一個CakePHP應用程序,該應用程序允許用戶創建帖子併爲其添加標籤(主題)。數據庫和關聯的結構可以在這裏看到:Setting up contains for a join table in CakePHP保存需要唯一的關聯模型數據

我已經成功地使用Contain通過連接表拉出數據。但現在我試圖構建用戶輸入主題的部分,然後將它保存在主題表和Topic_post表中。

我有下面的代碼我增加新的崗位方法:

if ($this->request->is('post')) 
     { 
      //$this->Post->create(); 

      if ($this->Post->save($this->request->data)) 
      { 
       // Save extra data 
       $this->Post->saveField('user_id', $this->Auth->user('id')); 
       $this->Post->saveField('datetime', date('Y-m-d H:i:s')); 
       $this->Post->saveField('modified', date('Y-m-d H:i:s')); 
       $this->Post->saveField('status', 1); 

       // Build slug 
       $post_title = Sanitize::html($this->request->data['Post']['title'], array('remove'=>true, 'quotes' => ENT_NOQUOTES)); 
       $post_title = String::truncate($post_title, 50, array('exact'=>false,'html'=>false,'ending'=>'')); 
       $this->Post->saveField('slug', Inflector::slug($post_title)); 

       // Redirect the user to the newly created post (pass the slug for performance) 
       $this->redirect(array('controller'=>'posts','action'=>'view','id'=>Tiny::toTiny($this->Post->id),'slug'=>$this->Post->slug)); 
      } 
      else 
      { 
       $this->Session->setFlash('Server broke!'); 
      } 
     } 

所以我現在需要做的是保存其鍵入此視圖相關主題數據:

<?php echo $this->Form->create(); ?> 

<?php echo $this->Form->input('Post.title'); ?> 

<?php echo $this->Form->input('Post.content', array('type'=>'textarea','label'=>false)); ?> 

<?php echo $this->Form->input('Topic.title', array('type'=>'textarea','label'=>'Topics')); ?> 

<button type="submit" class="orangeButton small">Create</button> 

<?php echo $this->Form->end(); ?> 

我看過CakePHP文檔,它看起來像saveAll是我需要的東西?但我很困惑,因爲我不能100%確定如何使用它也很重要的一點是,用戶可以將多個主題保存到數據庫,而主題本身都是唯一的,例如,您不能創建已經存在的主題,而只是使用鏈接器的現有ID。

任何人都可以幫忙嗎?因爲我覺得這是相當複雜的...

+0

有沒有更新?謝謝 – Cameron 2012-04-09 14:34:55

回答

2

你可以這樣做:


$this->Post->saveAll($this->data, array('validate'=>'first')); 

使用數組(「驗證」 =>「第一」);確保我們的兩個模型在保存前都經過驗證。你是不是這個意思。

希望它有幫助

+0

我不完全確定。我的意思是,CakePHP只是自動處理所有的聯繫,並知道哪些表放在哪裏?即。更新Post表,Topic表和Topic_Posts連接表? – Cameron 2012-04-09 09:58:55

+1

cakePHP會處理它,如果你有mantained關係,如Topic belongsTo Post等 – 2012-04-09 10:00:58

+0

那麼逗號分隔標籤雖然呢?蛋糕怎麼知道爲每個蛋糕創建一個連接併爲它們建立鏈接? – Cameron 2012-04-09 10:03:46