2016-07-27 96 views
0

我有產品表和productlines表。產品與產品線有關係。我想擁有一個搜索框並從產品表中搜索產品表和字段中的字段。Yii2單個搜索框從兩個不同的表中搜索字段

我的產品搜索模式

public function search($params) 
    { 
     $query = Product::find()->where(['product_id' => $this->getProductID()]); 

     // add conditions that should always apply here 
     $query->joinWith('productlines'); 

     $dataProvider = new ActiveDataProvider([ 
      'query' => $query, 
     ]); 

     $this->load($params); 

     if (!$this->validate()) { 
      // uncomment the following line if you do not want to return any records when validation fails 
      // $query->where('0=1'); 
      return $dataProvider; 
     } 

     // grid filtering conditions 
     $query->andFilterWhere([ 
      'product_id' => $this->product_id, 
      'product_region' => $this->product_region, 
      'product_created' => $this->product_created, 
      'product_lastchecked' => $this->product_lastchecked, 
      'sdsref_id' => $this->sdsref_id, 

     ]); 

     // var_dump($this->getProductID()); exit(); 
     $query->andFilterWhere(['like', 'product_name', $this->product_name]) 
      ->andFilterWhere(['like','product_id', $this->product_id]) 
      ->orFilterWhere(['like', 'product_catalog', $this->code]) 
      ->andFilterWhere(['=', 'product_aka', $this->product_aka]) 
      ->orFilterWhere(['like', 'internal_code' , $this->code]); 

     return $dataProvider; 
    } 

當我這樣做,我得到的錯誤:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'product_id' in where clause is ambiguous 
The SQL being executed was: SELECT COUNT(*) FROM `sim_product` LEFT JOIN `sim_productlines` ON `sim_product`.`product_id` = `sim_productlines`.`product_id` WHERE ((`product_id` IN ('2', '3')) OR (`product_catalog` LIKE '%A%')) OR (`internal_code` LIKE '%A%') 

誰能幫助我我該怎麼錯在何處,什麼可以是可能的解決方案。

感謝

+0

前綴表名' WHERE((tableName.product_id'。Mysql無法解析列名,因爲兩個表都有相同的名稱。 –

+0

如果我添加表名罰款欄 –

+0

使用queryBuilder。 –

回答

0

Yii2允許你把前綴列名ActiveQuery如:

$query->andFilterWhere(['like', 'product.product_name', $this->product_name]) 
    ->andFilterWhere(['like','productline.product_id', $this->product_id]) 
    ->orFilterWhere(['like', 'productline.product_catalog', $this->code]) 
    ->andFilterWhere(['=', 'product.product_aka', $this->product_aka]) 
    ->orFilterWhere(['like', 'product.internal_code' , $this->code]); 

來源:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data

參看 「有關係加入」