我有一个名为 items
的表和一个名为 item_pics
的表.
item_pics
有一个 item_id
, file_name
和一个 rank
领域(除其他外)。
我正在寻找的内容适用于每个 item
我的index
页面的$items
包含 file_name
的数组来自item_pics
匹配item
的item_id
最低rank
。所以我可以在我的 Items/index.ctp
中访问类似的内容(或类似的东西) :
foreach ($items as $item):
$img = $item['Item']['ItemPic']['file_name'];
...
<小时/>
我对 CakePHP 还很陌生,这是我的第一个项目。我认为这在Item
内模型会导致item_pics
要提取的数据(尽管我认为每个 item_pics
的所有相关 item
都会被提取,而不仅仅是具有最低 rank
的数据):
public $hasMany = array(
'ItemPic' => array(
'className' => 'ItemPic',
'foreignKey' => 'item_id',
'dependent' => false
)
}
但我可以看到没有item_pics
数据已加载(在 items/index
的底部):
SELECT `Item`.`id`, `Item`.`title`, `Item`.`description`, `Item`.`created`, `Item`.`modified`, `Item`.`type`, `Project`.`id`, `Project`.`item_id`, `Project`.`title`, `Project`.`description`, `Project`.`rank`, `Project`.`created`, `Project`.`modified`
FROM `laurensabc`.`items` AS `Item`
LEFT JOIN `laurensabc`.`projects`
AS `Project`
ON (`Project`.`item_id` = `Item`.`id`)
WHERE `Item`.`type` IN (1, 2)
LIMIT 20
另外,虽然我想要 projects
加入view
页面,我在 index
中并不真正需要它们页。
我进行了一些搜索,但未能找到我想要的内容。我想我可以在 index
内进行查询查看项目循环,但我试图确保我以正确的方式做事...... CakePHP 方式。我认为我需要改变我的模型关系,但我没有任何运气。
CakePHP - Associations - HasMany ,这使得我看起来可以按等级和限制 1 进行排序。但这不起作用......即使它起作用,我也不希望它影响 view
页面而不仅仅是 index
页。
我的 Controller 如下所示:
public function index($type = null) {
$this->Item->recursive = 0;
$conditions = array();
if ($type == "sale") {
$conditions = array(
"Item.type" => array(self::FOR_SALE, self::FOR_SALE_OR_RENT)
);
} else if ($type == "rent" ) {
$conditions = array(
"Item.type" => array(self::FOR_RENT, self::FOR_SALE_OR_RENT)
);
} else {
$conditions = array("Item.type !=" => self::HIDDEN);
}
$paginated = $this->Paginator->paginate($conditions);
debug($paginated);
$this->set('items', $paginated);
$this->set('title', ($type == null ? "Items for Sale or Rent" : "Items for " . ucwords($type)));
}
我也在我的 Controller 上尝试过这个,但它似乎也没有做任何事情:
$this->paginate = array(
'conditions' => $conditions,
'joins' => array(
array(
'alias' => 'ItemPic',
'table' => 'item_pics',
'type' => 'left',
'conditions' => array('ItemPic.item_id' => 'Item.id'),
'order' => array('ItemPic.rank' => 'asc'),
'limit' => 1
)
)
);
$paginated = $this->paginate($this->Item);
最佳答案
首先,在 AppModel 中设置 containable
行为(或者,如果您不想在每个模型上都使用它,请将其放在 Item
模型上):
public $actsAs = array('Containable');
然后,在您的查找查询中:
$items = $this->Item->find('all', array(
'contain' => array(
'ItemPic' => array(
'fields' => array('file_name'),
'order' => 'rank',
'limit' => 1
)
)
));
然后您可以像这样访问结果数组:
foreach ($items as $item):
$img = $item['ItemPic']['file_name'];
编辑:然后你应该把它放在分页查询上:
$this->paginate = array(
'conditions' => $conditions,
'contain' => array(
'ItemPic' => array(
'fields' => array('file_name'),
'order' => 'rank',
'limit' => 1
)
)
);
关于php - 包括相关表中的单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21835717/