2

例如,我有这样的关系:

UserContact hasMany Contact
Contact hasOne Info
Contact hasMany Response

而且我需要对联系人进行分页,所以我使用了 Containable:

$this->paginate = array(
            'limit'=>50,
            'page'=>$page,
            'conditions' =>array('Contact.id'=>$id),
            'contain'=>array(
                'Response',
                'Info'
                )
            );

我想通过 Info.name 和 Response.description 添加搜索。它非常适合Info.name ,但如果我尝试使用Response.description ,它会引发错误,说该列不存在。

此外,我尝试将关系更改为 Contact hasOne Response,然后正确过滤,但它只返回第一个响应,这不是正确的关系。

因此,例如,如果我有一个搜索键$filter我只想返回那些具有匹配Info.name或至少一个匹配Response.description的联系人。

4

2 回答 2

3

如果您查看 CakePHP 如何构造 SQL 查询,您会发现它在主查询中生成包含的“单一”关系(hasOnebelongsTo)作为连接子句,然后它为包含的“多重”关系添加单独的查询。

这使得通过单个关系进行过滤变得轻而易举,因为相关模型的表已经连接到主查询中。

为了通过多重关系进行过滤,您必须创建一个子查询:

// in contacts_controller.php:
$conditionsSubQuery = array(
  'Response.contact_id = Contact.id',
  'Response.description LIKE' => '%'.$filter.'%'
);
$dbo = $this->Contact->getDataSource();
$subQuery = $dbo->buildStatement(array(
    'fields' => array('Response.id'),
    'table' => $dbo->fullTableName($this->Contact->Response),
    'alias' => 'Response',
    'conditions' => $conditionsSubQuery
), $this->Contact->Response);
$subQuery = ' EXISTS (' . $subQuery . ') ';

$records = $this->paginate(array(
    'Contact.id' => $id,
    $dbo->expression($subQuery)
));

但是,如果您需要按Response字段过滤,则应该只生成子查询,否则您将过滤掉没有响应的联系人。

PS。这段代码太大太丑,无法出现在控制器中。对于我的项目,我将其重构为app_model.php,以便每个模型都可以生成自己的子查询:

function makeSubQuery($wrap, $options) {
    if (!is_array($options))
        return trigger_error('$options is expected to be an array, instead it is:'.print_r($options, true), E_USER_WARNING);
    if (!is_string($wrap) || strstr($wrap, '%s') === FALSE)
        return trigger_error('$wrap is expected to be a string with a placeholder (%s) for the subquery. instead it is:'.print_r($wrap, true), E_USER_WARNING);

    $ds = $this->getDataSource();

    $subQuery_opts = array_merge(array(
        'fields' => array($this->alias.'.'.$this->primaryKey),        
        'table' => $ds->fullTableName($this),        
        'alias' => $this->alias,   
        'conditions' => array(),     
        'order' => null, 
        'limit' => null,
        'index' => null, 
        'group' => null
    ), $options);

    $subQuery_stm = $ds->buildStatement($subQuery_opts, $this);
    $subQuery = sprintf($wrap, $subQuery_stm);
    $subQuery_expr = $ds->expression($subQuery);
    return $subQuery_expr;
}

然后控制器中的代码变为:

$conditionsSubQuery = array(
    'Response.contact_id = Contact.id',
    'Response.description LIKE' => '%'.$filter.'%'
);
$records = $this->paginate(array(
    'Contact.id' => $id,
    $this->Contact->Response->makeSubQuery('EXISTS (%s)', array('conditions' => $conditionsSubQuery))
));
于 2012-01-08T21:29:11.637 回答
0

我现在无法尝试,但如果您对 Response 模型而不是 Contact 模型进行分页,它应该可以工作。

于 2012-01-06T22:51:20.750 回答