这是行动网址
http://localhost/carsdirectory/cars/home
cars_controller.php(控制器)
public function home(){
$this->set('latest_cars', $this->Car->find('all', array(
'order' => array(
'Car.modified DESC',
'Car.created Desc'
),
'limit' => '3'
)));
$this->set('galleries', $this->Gallery->find('all'));
}
car.php(模型)
public $hasMany = array(
'Gallery' => array(
'className' => 'Gallery',
'foreignKey' => 'car_id',
'dependent' => true
)
);
gallery.php(模型)
var $belongsTo = array(
'Car' => array(
'className' => 'Car',
'foreignKey' => 'car_id',
)
);
home.ctp(视图)
<?php foreach($latest_cars as $latest_car){ ?>
<img src="img/car-listings.jpg" /> // now it's static
<h4><?php echo $latest_car['Car']['car_name']; ?></h4> // it's dynamic it's coming car table
<span>$<?php echo $latest_car['Car']['car_price']; ?></span> // it's dynamic it's coming car table
<?php } ?>
我已经替换了该行
<img src="img/car-listings.jpg" />
用那一行
<?php $this->Html->image('/media/filter/small/'.$latest_cars['Gallery']['dirname'].'/'.$latest_cars['Gallery']['basename']);?>
但我得到了那个错误
未定义索引:图库[APP \ views \ cars \ home.ctp,第226行]
<img src="img/car-listings.jpg" /> this line i want to make dynamic , so my question how to use join in cars_controller or any other idea and i want to fetch data from galleries table
这是画廊表结构
id - 1
basename - chrysanthemum_10.jpg
car_id - 1
提前致谢
答案 0 :(得分:2)
因此,您拥有Car
模型和Gallery
模型。由于Gallery
具有car_id
属性,因此可以用它来形成这些CakePHP Associations:
图库属于汽车
和
Car hasOne Gallery
您可以选择实际需要的关联,并在模型中定义它们。在您的情况下,您想要在查询汽车时显示汽车的画廊,所以:
// in car.php
var $hasOne = 'Gallery';
然后,您可以选择是否要使用Containable来控制哪些关联包含在查询中,或者只使用recursive
来包含所有关联:
// in cars_controller.php
$this->set('latest_cars', $this->Car->find('all', array(
'recursive' => 1,
'order' => array(
'Car.modified DESC',
'Car.created Desc'
),
'limit' => '3'
)));
然后在您的视图中,使用$latest_car['Car']
访问汽车属性,使用$latest_car['Gallery']
访问图库属性
修改强>
如果Car
有多个Gallery
,那么您应该期待这种结构:
[0] =>
Car => (first car)
Gallery =>
[0] => (first gallery of first car)
[1] => (second gallery of first car)
[1] =>
Car => (second car)
Gallery =>
[0] => (first gallery of second car)
etc.
以便在您的视图中访问它:
<?php
foreach($latest_cars as $latest_car){
foreach ($latest_car['Gallery'] as $gallery)
echo $this->Html->image('/media/filter/small/'.$gallery['dirname'].'/'.$gallery['basename']);
?>
答案 1 :(得分:1)
在Controller find中使用join,根据需要指定字段
$results= $this->Car->find('all',
array('fields'=> array('Car.*','galleries.*'),
'joins'=> array(
array('table'=>'galleries', 'type'=>'inner',
'conditions'=>array('Car.car_id=galleries.car_id'))
))
)
答案 2 :(得分:0)
在控制器文件中添加此行
$this->loadModel('Table');//table is your model name in singular
$this->set('table', $this->Table->find('all'));
你可以直接在视图中使用$ table,如果你与table有关系,你可以使用CakePHP提供的默认关系
谢谢