我有3个表:productions
,chunks
(生产可能有很多块,因此chunks
包含production_id
列)和chunk_designers
(块)可能有很多设计师,因此chunk_designers
有一列chunk_id
)。
我必须在CGridView中从productions
呈现数据并添加一列:块的数量(表中每个生产项的),这些块未分配给任何块。换句话说:
SELECT COUNT(*) FROM `chunks`
left JOIN `chunk_designers`
ON chunks.id = chunk_designers.chunk_id
WHERE production_id = 520 AND chunk_id IS null
...其中520 - 每行的动态值productions.id
。
ChunkController
行动:
function actionProductionList() {
$model = new Productions('search');
$model->unsetAttributes(); // clear any default values
$dataProvider = $model->search($_GET);
$dataProvider->criteria->order = 'start_time DESC';
$this->render('production_list', array(
'provider' => $dataProvider,
'model' => $model,
));
}
模型Productions
:
class Productions extends AppModel {
....
public $unassignedBlocksCount;
....
public function rules() {
return array(
array('unassignedBlocksCount, id, ...', 'safe'),
array('unassignedBlocksCount, id, ...', 'safe', 'on'=>'search'),
);
}
//in search() I added:
$criteria->compare('unassignedBlocksCount', $this->unassignedBlocksCount, true);
}
并且在视野中:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'menu-grid',
'dataProvider' => $provider,
'filter' => $model,
'enablePagination' => true,
'columns' => array(
array(
'name' => 'unassignedBlocksCount',
'value' => 'Chunks::getUnassignedBlocksCount($data->id)'
),
...
列数据呈现正常,但当我尝试过滤它时,我收到以下错误:unknown column unassignedBlocksCount in where clause
。
我尝试在search()
模型中使用Productions
方法编写:
// subquery to retrieve the count of posts
$count_sql = "(SELECT COUNT(*) FROM `chunks` "
. "LEFT JOIN `chunk_designers` "
. "ON chunks.id = chunk_designers.chunk_id "
. "WHERE production_id = 520 AND chunk_id IS NULL)";
// select
$criteria->select = array(
'*',
$count_sql . " as unassignedBlocksCount",
);
刚刚在unassignedBlocksCount
中添加了columns
元素。
但我仍然会遇到相同的错误,过滤时,还有一个问题是我不知道如何动态production_id
$count_sql
动态取决于每个表格行(&& #39;为什么该列值的每一行都为1,因为production_id
= 520的正确值。
所以,我的问题是:如何在CGridView中获取可排序和可过滤的列,该列由其他表中的数据计算(COUNT()
)?提前谢谢。