我試圖遍歷CakePHP模型上的關係。 這是數據庫: 如何遍歷CakePHP關係?
我可以訪問產品屬性(產品 - >屬性)上的產品型號,但我不能訪問AD模型(AD->產品 - >屬性)的產品屬性。
這裏是我的代碼:
//Product Model class Product extends AppModel { public $useTable = 'products'; public $displayField = 'name'; public $hasAndBelongsToMany = array( 'Attributes' => array( 'className' => 'Attribute', 'joinTable' => 'product_has_attributes', 'foreignKey' => 'products_id', 'associationForeignKey' => 'attributes_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'with' => 'product_has_attributes' ) ); public $hasMany = array( 'Ads' => array( 'className' => 'Ad', 'foreignKey' => 'Products_id', 'conditions' => '', 'order' => '', 'limit' => '', 'dependent' => true ) ); //Ad Model class Ad extends AppModel { public $displayField = 'Name'; public $belongsTo = array( 'Product' => array( 'className' => 'Products', 'foreignKey' => 'products_id', 'conditions' => '', 'fields' => '', 'order' => '' ) ); //Attribute Model class Attribute extends AppModel { public $displayField = 'name'; public $hasAndBelongsToMany = array( 'Products' => array( 'className' => 'Product', 'joinTable' => 'product_has_attributes', 'foreignKey' => 'attributes_id', 'associationForeignKey' => 'products_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'with' => 'product_has_attributes' ) );
// Products controller -> Action View class ProductsController extends AppController { public function view($id = null) { if (!$this->Product->exists($id)) { throw new NotFoundException(__('Invalid product')); } $options = array('conditions' => array('Product.' . $this->Product->primaryKey => $id)); $this->set('product', $this->Product->find('first', $options)); } }
// Ads controller -> Action View class AdsController extends AppController { public function view($id = null) { if (!$this->Ad->exists($id)) { throw new NotFoundException(__('Invalid ad')); } $options = array('conditions' => array('Ad.' . $this->Ad->primaryKey => $id)); $this->set('ad', $this->Ad->find('first', $options));
}
這裏是我做的觀點:
//產品瀏覽:view.ctp
的print_r的snipet( $產品);
//此打印RHE產品和所有相關的屬性
//廣告瀏覽次數:view.ctp
的print_r($廣告[ '產品'])的snipet;
//這將只打印產品字段,但不打印與產品關聯的屬性
什麼是錯的?如何從我的廣告模型訪問關係Ad-> product->屬性?
使用的print_r($廣告);而不是print_r($ product); –