我有一个表格,其中包含有关这些网站的URL和信息。每个URL可以出现一次或两次。该站点的首次扫描和最后一次扫描。我想在GridView中通过URL和第一次扫描等级显示数据,如果存在第二次扫描等级。当我加载所有时,我会得到正确的数据。URL,等级,2年级。但是,当我尝试按等级搜索时,我只会得到两次扫描的站点,因此它们在数据库中两次,并且仅忽略了数据库中的网站。
table:
id url initial points grade
1 blue.com 1 10 F
2 red.com 1 20 F
3 blue.com 0 50 C
etc...
display in gridview works fine
no url points grade points2 grade2
1 blue.com 10 F 50 C
2 red.com 20 F not set not set
etc...
但是,当我通过URL搜索或等级时,它仅显示在表中具有第二个扫描的结果
模型:
public function getParent() {
return $this->hasOne(self::classname(), ['url' => 'url'])->
from(self::tableName() . ' AS parent')-
>onCondition(['parent.initial'=>0]);
}
public function getParentid(){
return $this->parent->id;
}
public function getParentgrade(){
return $this->parent->grade;
}
public function getParentpoints(){
return $this->parent->points;
}
在搜索模型中:
public $parentid;
public $parentpoints;
public $parentgrade;
public function rules()
{
return [
[[........'parentpoints'.........], 'integer'],
[['url', 'parentgrade', .........], 'safe'],
];
}
public function search($params)
{
$query = SitesTemp::find();
$query->where(['sites_temp.for_scan'=>0, 'sites_temp.initial'=>1]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes'=>[
'url',
'points',
'grade',
'parentgrade'=>[
'asc'=>['parent.grade'=> SORT_ASC],
'desc'=>['parent.grade'=> SORT_DESC],
'label'=>'Last Grade'
],
'parentpoints'=>[
'asc'=>['parent.points'=> SORT_ASC],
'desc'=>['parent.points'=> SORT_DESC],
'label'=>'Last Points'
],
]
]);
$this->load($params);
if (!($this->load($params) && $this->validate())) {
$query->joinWith(['parent']);
return $dataProvider;
}
$query->andFilterWhere([
'sites_temp.id' => $this->id,
'sites_temp.initial' => $this->initial,
'sites_temp.points' => $this->points,
]);
$query->andFilterWhere(['like', 'sites_temp.url', $this->url])
->andFilterWhere(['like', 'sites_temp.grade', $this->grade])
->andFilterWhere(['like', 'sites_temp.points', $this-
>points]);
$query->joinWith(['parent'=>function($q){
$q->where('parent.grade like "%'.$this->parentgrade.'%"');
}]);
return $dataProvider;
}
}
我弄清楚了。
我只需要在存在搜索参数时才能将JoinWith放置。所以
if(!empty($this->parentgrade)){
$query->joinWith([parent=>function($q){
$q->where('parent.grade like "%'.$this->parentgrade.'%"');
}]); }
解决了我的问题