简体   繁体   中英

Yii. CActiveDataProvider and has many relation

I have two models: Document and Report. One document could have from 0 or several reports. One report belongs to 0 or 1 Document.

class Document extends CActiveRecord {
    public function relations() {
        return array(
            'reports' => array(self::HAS_MANY, 'Report', 'document_id')
        );
    }
}

class Report extends CActiveRecord {
    public function relations() {
        return array(
            'document' => array(self::BELONGS_TO, 'Document', 'document_id')
        );
    }
}

field document_id can be null.

I would like to display table using CGridView widget. Table contains column "document name" and "report name". If document does not have report put only "document name" and keep "report name" blank. If document has one or more reports put one row for each report. Example:

+--------+-------------+
|Doc name| Report name |
+--------+-------------+
|doc1    |             |
|doc2    | report1     |
|doc3    | report2     |
|doc3    | report3     |
+--------+-------------+

When I tried to create CActiveDataProvider in this way:

$criteria = new CDbCriteria();
$criteria->with = [
    'reports' => [
       'together' => true,
]
$params = [
    'criteria' => $criteria,
];
$dataProvider = new CActiveDataProvider('Document', $params);

For each document I get 1 row, even if document has several reports.

If I do in this way:

$criteria = new CDbCriteria();
$params = [
    'criteria' => $criteria,
];
$criteria->with = [
    'document' => [/*...*/],
]
$dataProvider = new CActiveDataProvider('Report', $params);

Documents with 0 reports are missing.

How can I do this?

使用CSqlDataProvider而不是CActiveDataProvider解决。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM