我已将我的数据提供者设置为左连接为
$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中的数据
答案 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
)。根据您的查询。