[英]How to create model for search for multi table in yii2
I want to search in a multi table in yii2.我想在 yii2 中的多表中搜索。 How to do this action?这个动作怎么做?
<?php
namespace app\models;
use Yii;
use yii\db\Query;
use app\models\Article;
use app\models\Certificates;
use app\models\News;
use app\models\Pages;
use app\models\Projects;
use app\models\NewsSearch;
i want search in multi table.我想在多表中搜索。 that table have not any relation with Together那张桌子和Together没有任何关系
i want write query in yii2 like this :我想在 yii2 中这样写查询:
select * from news , article , projects where (any column for this tables ) like %search%
You can do it using relation adding the activeRelation the your main model and then use the relation in a proper search function您可以使用关系将 activeRelation 添加到您的主模型中,然后在适当的搜索功能中使用该关系
eg ( just a brief suggestion) :例如(只是一个简短的建议):
/* ActiveRelation */
public function getMyExtModelRelation()
{
return $this->hasOne(MyExtModel::className(), ['id' => 'ext_id']);
}
and in main modelSearch并在主模型搜索中
/* search function */
.....
....
// filter by MyExtModel attribute
$query->joinWith(['myExModelRelation' => function ($q) {
$q->where('tbl_my_ext_model.my_attribute LIKE "%' . $this->my_attribute . '%"');
}]);
Here you can find a good tutorial for common related and calculated search filter and sort http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/在这里你可以找到一个很好的教程,用于常见的相关和计算的搜索过滤器和排序http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2- 0/
I don't understand what you are trynd to do and the result of your query could be huge and of little use but anyway if you want a genaric query you can use我不明白你想做什么,你的查询结果可能很大而且用处不大,但无论如何,如果你想要一个通用查询,你可以使用
use yii\db\Query;
.....
$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();
could be you must assign alias to the column that you use in select for retrive this column from models or use the complete name (tablename.columnname)可能是您必须为您在 select 中使用的列分配别名以从模型中检索此列或使用完整名称 (tablename.columnname)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.