2016-06-10 56 views
1

我是Yii2框架的新手,我現在試圖使用關係訪問Listview中的數據。有人可以解釋爲什麼我的代碼不工作。 我想找到一個屬於文檔的標籤。訪問Yii2中的數據

這裏是我的數據庫的截圖: enter image description here

這裏是我的關係:

public function getTags() { 
    return $this->hasMany(Tag::className(), ['id' => 'tag_id']) 
        ->viaTable('tbl_document_tag', ['document_id' => 'id']); 
} 

這裏是我的控制器:

public function actionTag() { 
    $model = new Search(); 
    $tag = Yii::$app->getRequest()->getQueryParam('tag'); 

    //Documents 
    $documentModel = new Document; 
    $documentSearch = $model->searchDocumentsByTag($documentModel, $tag); 

    return $this->render('results', [ 
     'model' => $model, 
     'documentSearch' => $documentSearch, 
     'documentModel' => $documentModel 
    ]); 
} 

這是我的觀點:

public function searchDocumentsByTag($documentsModel, $keyword) { 
    $query = Document::find() 
      ->with('tags') 
      ->andFilterWhere([ 
     'or', 
     ['like', 'tags.state', 1], 
     ['like', 'tags.slug', $keyword], 
    ]); 

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

我得到以下錯誤:

Database Exception – yii\db\Exception

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags.state' in 'where clause' The SQL being executed was: SELECT COUNT(*) FROM tbl_document WHERE (tags . state LIKE '%1%') OR (tags . slug LIKE '%steekwoord%') Error Info: Array ( [0] => 42S22 1 => 1054 [2] => Unknown column 'tags.state' in 'where clause' ) ↵ Caused by: PDOException

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags.state' in 'where clause'

+2

你的代碼不工作?你收到什麼錯誤?您需要描述您嘗試實現的結果 – mikeyq6

+0

嘗試使用此類結果,例如'['like','tbl_tag.state',1],['like','tbl_tag.slug',$ keyword]' – vishuB

回答

1

您只需要使用joinWith()代替with()

This method allows you to reuse existing relation definitions to perform JOIN queries. [...] Note that because a JOIN query will be performed, you are responsible to disambiguate column names.

例如:

$query = Document::find() 
    ->joinWith('tags tags') 
    ->andFilterWhere([ 
     'or', 
     ['like', 'tags.state', 1], 
     ['like', 'tags.slug', $keyword], 
    ]); 
+0

Thanks,It's工作中 :) –