yii 1关系在CGridView中不起作用

时间:2015-09-21 03:18:30

标签: mysql gridview yii yii-relations

我试图获得companies表具有主键companyIDdivision表具有外键companyID的关系,我在where子句中需要{{1 }} 我的模型中的关系是:

WHERE companies.companyID = division.companies

我的public function relations() { return array( 'company' => array(self::BELONGS_TO, 'Companies', 'CompanyID'), ); } 功能

Model->search()

我的public function search() { $criteria=new CDbCriteria; $criteria->with ='company'; $criteria->compare('company.CompanyID', $this->CompanyID, true ); $criteria->compare('DivisionID',$this->DivisionID, true); $criteria->compare('CompanyID',$this->CompanyID, true); $criteria->compare('Name',$this->Name,true, true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } 视图是:

admin.php

3 个答案:

答案 0 :(得分:1)

您需要将together=true添加到您的条件中。

$criteria->together = true;

它会添加连接到查询。有关延迟加载的一些信息http://www.yiiframework.com/wiki/527/relational-query-lazy-loading-and-eager-loading-with-and-together/

答案 1 :(得分:1)

如果您想显示公司名称,只需在视图中执行此操作。不要更改模型中的任何内容 - > search()。     阵列(           '名称'=> '名称',           'value'=> $ model-> company-> name //此处name是公司表中的列名。           ),

答案 2 :(得分:0)

在gridview代码中,请执行以下更改。

$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'divisions-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
        array(
            'name' => 'companies',//fied from division table which refers to companyId from company table.
            'header' => 'Company',
            'value' => '$data->company->company_name'
        ),
        'CompanyID',
        'DivisionID',
        'Name',
        array(
            'class' => 'CButtonColumn',
        ),
    ),
));

在您的模型中 - >搜索()

public function search()
{
    $criteria=new CDbCriteria;
    $criteria->with ='company';
    $criteria->compare('company.company_name', $this->companies, true );
    $criteria->compare('DivisionID',$this->DivisionID, true);
    $criteria->compare('CompanyID',$this->CompanyID, true);
    $criteria->compare('Name',$this->Name,true, true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}