2016-06-10 55 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工作中 :) –