Possible Duplicate:
CakePHP: Call to a member function find() on a non-objectвызов функции члена находке() на не-объект CakePHP
У меня есть три модели: Продукт, Prodpage, Field.
Я сделал консоль для торта, чтобы испечь все модели на основе моего локального mysql db на моем компьютере. Затем я создал простой контроллер для каждой модели, используя общедоступный $ scaffold. Вот пример ProductsController:
<?php
// app/Controller/ProductsController.php
class ProductsController extends AppController {
public $scaffold;
}
вошел в мое приложение (локальный/торт/продукты) и все работало нормально. Я мог бы добавлять продукты, удалять продукты, редактировать продукты. Затем я мог бы добавить prodpages, и я мог бы также добавить поля. Я решил пойти дальше и использовать консоль для торта, чтобы испечь контроллеры и представления. Я понял, что он должен делать то же самое, что и $ scaffold, но на этот раз контроллеры должны иметь больше кода в нем. Таким образом, позвольте мне начать настраивать его немного больше.
Я возвращаюсь к localhost/cake/products, и он отлично работает. Затем, когда я пытаюсь перейти к локальной машине/торт/prodpages/добавить, и я получаю эту ошибку:
Fatal error: Call to a member function find() on a non-object in C:\wamp\www\cake\app\Controller\ProdpagesController.php on line 50
Вот ProdpagesController все они, как по линии 53 (функция дополнения):
<?php
App::uses('AppController', 'Controller');
/**
* Prodpages Controller
*
* @property Prodpage $Prodpage
*/
class ProdpagesController extends AppController {
/**
* index method
*
* @return void
*/
public function index() {
$this->Prodpage->recursive = 0;
$this->set('prodpages', $this->paginate());
}
/**
* view method
*
* @param string $id
* @return void
*/
public function view($id = null) {
$this->Prodpage->id = $id;
if (!$this->Prodpage->exists()) {
throw new NotFoundException(__('Invalid prodpage'));
}
$this->set('prodpage', $this->Prodpage->read(null, $id));
}
/**
* add method
*
* @return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Prodpage->create();
if ($this->Prodpage->save($this->request->data)) {
$this->Session->setFlash(__('The prodpage has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The prodpage could not be saved. Please, try again.'));
}
}
$products = $this->Prodpage->Product->find('list');
$this->set(compact('products'));
}
и это линия 50,
$products = $this->Prodpage->Product->find('list');
Кто-нибудь знает, что я делаю неправильно здесь или уточнить, что говорит мне об ошибке? Я новичок в cakephp, поэтому я иду по учебникам. Тем не менее, это меня озадачило.
Обновление: Модель/product.php
<?php
App::uses('AppModel', 'Model');
/**
* Product Model
*
* @property Prodpages $Prodpages
*/
class Product extends AppModel {
/**
* Display field
*
* @var string
*/
public $displayField = 'product_name';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'product_name' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
's7_location' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'modified' => array(
'datetime' => array(
'rule' => array('datetime'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
'Prodpages' => array(
'className' => 'Prodpages',
'foreignKey' => 'id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
Вот модель/Prodpage.php
<?php
App::uses('AppModel', 'Model');
/**
* Prodpage Model
*
* @property Products $Products
* @property Fields $Fields
*/
class Prodpage extends AppModel {
/**
* Display field
*
* @var string
*/
public $displayField = 'page_name';
/**
* Validation rules
*
* @var array
*/
public $validate = array(
'is_blank' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'page_order' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
's7_page' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'modified' => array(
'datetime' => array(
'rule' => array('datetime'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* @var array
*/
public $belongsTo = array(
'Products' => array(
'className' => 'Products',
'foreignKey' => 'products_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* @var array
*/
public $hasMany = array(
'Fields' => array(
'className' => 'Fields',
'foreignKey' => 'id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
Я сделал торт консоли, чтобы испечь эти модели, так что я сделал ассоциации внутри там. Я думал, что правильно обработал Prodpage и Product. У одного продукта может быть много Prodpages. Одна Prodpage относится к одному продукту.
UPDATE W/QUERY ОШИБКА
Так что, когда я иду на локальный/торт/prodpages/добавить и заполнить информацию, выбрав продукт из списка продукт ниспадающего я получаю эту ошибку
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`builder_cake`.`prodpages`, CONSTRAINT `fk_prodpages_products` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Query: INSERT INTO `builder_cake`.`prodpages` (`page_name`, `is_blank`, `page_order`, `s7_page`, `modified`, `created`) VALUES ('Page 2', '0', 2, 2, '2012-06-13 16:51:35', '2012-06-13 16:51:35')
Я просмотрел его и не передал product_id, связанный с выпадающим списком, чтобы добавить его в столбец product_id в моей таблице Prodpages .. любые мысли почему?
Это означает, что '$ this-> Prodpage-> Product' не существует, что, вероятно, связано с тем, что Prodpage не относится к Продукту. – jeremyharris
Я редактировал сообщение с помощью моделей Product и Prodpage. Я думал, что правильно их связал .. есть ли что-то еще? или я сделал их не так? – thindery
Возникла проблема с вашим именем модели.У вас есть Продукт ** s **, где он должен быть исключительным: Продукт. Если ваше имя модели - это действительно продукты, то используйте '$ this-> Prodpage-> Products'. То же самое касается Fields. – jeremyharris