简体   繁体   中英

Yii2 ActiveDataprovider get the related fields data

I have setup my dataprovider with left join as

$trucks = TblTrucks::find()
                  ->leftJoin("tbl_checks", "tbl_checks.truck_id=tbl_trucks.id")
                  ->Where(["town"=>$town])

                  ->andWhere(["truck_status"=>6])
                  ->andWhere(["between","tbl_trucks.created_at", $ts1, $ts2 ]);


    $provider = new ActiveDataProvider([
        'query' => $trucks,
        'pagination' =>false,
    ]);

Now am getting thje data via

return $provider->getModels();

This returns only tbl_trucks data how can i still get the data in the tbl_checks

To get related field in model first of all your must have relation model TblChecks define relation in model TblTrucks acording to documentation In you case it will be some like that:

public function getTblChecks()
{
    return $this->hasOne(TblChecks::className(), ['truck_id' => 'id']);
    //or, depending on the type of relation (on-to-one or one-to-maty) 
    return $this->hasMany(TblChecks::className(), ['truck_id' => 'id']);
}

Than use method joinWith :

$trucks = TblTrucks::find()
              ->joinWith(['tblChecks'])
              ->Where(["town"=>$town])
              ->andWhere(["truck_status"=>6])
              ->andWhere(["between","tbl_trucks.created_at", $ts1, $ts2 ]);

And then you can get relation field just call it:

$models = $provider->getModels();
$models[index]->tblChecks->needed_field

But if you need just array of modesl acording to your query you dont have to use ActiveDataProvider just call method all() For example:

$trucks = TblTrucks::find()
              ->joinWith(['tblChecks'])
              ->Where(["town"=>$town])
              ->andWhere(["truck_status"=>6])
              ->andWhere(["between","tbl_trucks.created_at", $ts1, $ts2 ])->all();

And in var $trucks you will have array of models TblTrucks with relation models ( TblChecks in this case) acording to your query.

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