【问题标题】:How to create model for search for multi table in yii2如何在 yii2 中创建用于搜索多表的模型
【发布时间】:2016-10-04 13:33:40
【问题描述】:

我想在 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%

【问题讨论】:

    标签: php yii2 searchqueryset


    【解决方案1】:

    您可以使用关系将 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)

    【讨论】:

    • 我想在多表中搜索。该表与Together没有任何关系,我更新了这篇文章。
    • SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的 'concat('%', yes, '%')' 附近使用正确的语法正在执行的 SQL 是:select * from news, article where news.fTitle concat('%', 是的, '%'); !!!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多