CakePHP Model显示所有数据为null

时间:2014-04-30 08:47:58

标签: cakephp model controller

我无法显示数据。

我的模特(app / Model / Product.php)

class Product extends AppModel {
public $name = 'Product'; 
}

我的控制器(app / Controller / ProductsController.php):

class ProductsController extends AppController {
public $helpers = array('Html','Form','Session');
public $components = array('Session');
public $name = 'Products';

public function ver($id = null) {
$this->Product->id_producto = $id;
debug($this->Product->id_producto); //Show id with value Ex. 12,34,...
$this->set('products', $this->Product->read());
  }
}

我的观点(app / View / ver.ctp):

<?php debug($product['Product']['nombre']); ?> // Show 'null'
<h2><?php echo $product['Product']['nombre']?></h2></td></tr>
<strong>Descripci&oacute;n:</strong> <?php echo $product['Product']['descripcion']?> <br/>
<small>Fecha de registro: <?php echo $product['Product']['fecha_reg']?></small> <br/>
<small>Última modificación: <?php echo $product['Product']['Fecha_mod']?></small>

1 个答案:

答案 0 :(得分:2)

您没有使用默认主键:id。在模型中定义主键:

class Product extends AppModel
{
    public $primaryKey = 'id_producto';
}

...并在控制器中向id请求产品ID。 id将与数据库表中的主键id_producto匹配:

public function ver($id = null) 
{
    $this->Product->id = $id;
    debug($this->Product->id); //Show id with value Ex. 12,34,...;
    $this->set('product', $this->Product->read());
}

一些注意事项:

控制器中,您将结果分配给多个“产品”:

$this->set('products', $this->Product->read());

但是在视图中,您使用单数$product中的变量:

尝试改为使用<?php debug($products['Product']['nombre']); ?>