[英]How to create model for search for multi table in yii2
我想在 yii2 中的多表中搜索。 這個動作怎么做?
<?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;
我想在多表中搜索。 那張桌子和Together沒有任何關系
我想在 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 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();
可能是您必須為您在 select 中使用的列分配別名以從模型中檢索此列或使用完整名稱 (tablename.columnname)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.