Yii2 ActiveDataprovider获取相关的字段数据

时间:2017-08-31 07:31:06

标签: php yii2

我已将我的数据提供者设置为左连接为

$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,
    ]);

现在通过

获取数据
return $provider->getModels();

这只返回tbl_trucks数据如何仍然可以获取tbl_checks中的数据

1 个答案:

答案 0 :(得分:0)

要首先获取模型中的相关字段,您必须拥有关系模型TblChecks根据documentation定义模型TblTrucks中的关系 在你的情况下,它会是这样的:

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']);
}

比使用方法joinWith

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

然后你可以通过调用它来获得关系字段:

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

但是,如果您只需要根据您的查询进行一系列模式,则不必使用ActiveDataProvider只需调用方法all() 例如:

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

在var $trucks中,您将拥有一系列模型TblTrucks,其中包含关系模型(在本例中为TblChecks)。根据您的查询。