如何在yii2中创建多表搜索模型



我想在yii2中的多表中进行搜索。这个动作怎么做?

<?php
namespace appmodels;
use Yii;
use yiidbQuery;
use appmodelsArticle;
use appmodelsCertificates;
use appmodelsNews;
use appmodelsPages;
use appmodelsProjects;
use appmodelsNewsSearch;

我想在多表中搜索。

我想在yii2中这样写查询:

select *   from news , article , projects where (any column for this tables ) like %search%

您可以使用关系在主模型中添加activeRelation,然后在适当的搜索函数中使用该关系
(只是一个简短的建议):

/* ActiveRelation */
public function getMyExtModelRelation()
{
   return $this->hasOne(MyExtModel::className(), ['id' => 'ext_id']);
}

和在主模型搜索

/* search function  */ 
 .....
 ....
// filter by MyExtModel attribute
 $query->joinWith(['myExModelRelation' => function ($q) {
     $q->where('tbl_my_ext_model.my_attribute LIKE "%' . $this->my_attribute . '%"');
}]);

在这里你可以找到一个很好的教程,常见的相关和计算搜索过滤器和排序http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

我不明白你想做什么,你的查询结果可能是巨大的,没有什么用处,但无论如何,如果你想要一个通用查询,可以使用

use yiidbQuery;
.....
$connection = Yii::$app->db;
$any_column  = "your_any_column";
$any_search  = " concat('%', '". $your_search ."', '%'); "
$sql ="select *   from news, article , projects  where " . $any_column  . $any_search ;
$yourModels  = $connection->createCommand($sql);->queryAll();

可以是:您必须为在select中使用的列分配别名,以便从模型中检索该列,或者使用完整的名称(tablename.columnname)

最新更新