2

我正在尝试获取companies表具有主键companyIDdivision表具有外键的关系,我companyID在 where 子句中需要的是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观点是:

 <?php
$this->breadcrumbs = array(
    'Divisions' => array('index'),
    'Manage',
);

$this->menu = array(
    array('label' => 'List Divisions', 'url' => array('index')),
    array('label' => 'Create Divisions', 'url' => array('create')),
);

   ");
?>

<div class="row">
    <?php
    $this->renderPartial('_dropdownfilter', array(
        'model' => $model,
    ));
    ?>
</div><!-- end dropdown partial form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'divisions-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
        'CompanyID',
        'DivisionID',
        'Name',
        array(
            'class' => 'CButtonColumn',
        ),
    ),
));
?>
4

3 回答 3

1

您需要添加together=true到您的标准。

$criteria->together = true;

它将加入查询。关于延迟加载的一些信息http://www.yiiframework.com/wiki/527/relational-query-lazy-loading-and-eager-loading-with-and-together/

于 2015-09-21T07:03:09.160 回答
1

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

于 2015-09-21T10:15:44.123 回答
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,
    ));
}
于 2015-09-22T05:52:32.187 回答