2016-10-30 41 views
1

搜索相關表單一屬性我有兩個表一個檢查和卡車在yii2

,這是它們的結構:

table truck : has truckid, reg_no, truck_category 
table check : has truck_id(fkey from truck table), checkid.... 

同時使用卡車的ID在表檢查什麼我想要實現模型顯示tabletruck細節(reg_no,truck_category)

這是tblcheck模型的關係

public function getTruck() 
{ 
    return $this->hasOne(TblTrucks::className(), ['id' => 'truck_id']); 
} 

所以我做了一個搜索模式:

public function rules() 
{ 
    return [ 
     [['id', 'ref_no','done_by', 'done_at'], 'integer'], 
     [['checks_fails', 'done_on','truck_id'], 'safe'], 
    ]; 
} 

    public function search($params) 
{ 
    $query = Tblchecks::find(); 
    // add conditions that should always apply here 
    $query->joinWith('truck'); 
    $dataProvider = new ActiveDataProvider([ 
     'query' => $query, 
    ]); 

    $this->load($params); 

    // grid filtering conditions 
    $query->andFilterWhere([ 
     'id' => $this->id, 
     'ref_no' => $this->ref_no, 
     'check_has' => $this->check_has, 
     'done_by' => $this->done_by, 
     'done_at' => $this->done_at, 
     'done_on' => $this->done_on, 
    ]); 

    // here am filtering with the same truck_id 
    $query->andFilterWhere(['like', 'truck.company', $this->truck_id]); 
    $query->andFilterWhere(['like', 'truck.regno', $this->truck_id]); 


    return $dataProvider; 
} 

所以在我的網,我有

[ 
     'attribute' => 'truck_id', 
     'width'=>'310px', 
     'value'=>'truck.company', 
], 
[ 
     'attribute' => 'truck_id', 
     'header' => 'Truck number', 
     'value'=>'truck.regno', 
] 

以上不過濾我的網,我怎麼去篩選使用一個屬性網格這是一個外鍵來顯示相關的項目

+0

的truck.company和truck.regno從卡車或檢查表? .. – scaisEdge

+0

他們是從卡車表,但檢查模型發生在檢查表 –

+0

我不明白你有兩個表中的兩列? .. – scaisEdge

回答

1

我做這樣

模型

(你的情況tblcheck模型),用於相對於b中的每個領域需要妍uild getter函數

public function getTruck() 
{ 
    return $this->hasOne(TblTrucks::className(), ['id' => 'truck_id']); 
} 


// Getter for truck.company 
// this from the relation above (truck) return th field company 
public function getTruck_company() { 
    return $this->truck->company; 
} 

在搜索模型

// filter by company from Tblcheck 
     $query->joinWith(['truck' => function ($q) { 
      $q->where(truck_tabale_name.company LIKE "%' . $this->truck_company . '%"'); 
     }]); 

,並在網格視圖..只需使用的getter

[ 
    'attribute' => 'truck_company', 
    'width'=>'310px', 
],