我有一个Yii2查询对象,它包含执行全文搜索的方法
public function search($search)
{
return $this->andWhere('MATCH(title, description, tags) AGAINST(:search) AS value', ['search' => $search])
->orderBy('value');
}
整个代码看起来像
$dataProvider = new ActiveDataProvider([
'query' => Video::find()->published()->search($search)
]);
当然,这不起作用,因为Where((不允许AS值语句。有人能告诉我如何解决这个问题吗?非常感谢。
我想您可以在select子句中包含搜索部分,以便对结果进行排序
Video::find()
->published()
->search($search)
->select(['*','MATCH(title, description, tags) AGAINST(:search) AS value'])
->orderBy('value');
但问题是绑定:search
占位符的值(对此不确定(,为此,我想你可以使用以params为第二个参数的yiidbExpression
类,并且这个表达式可以在select()
方法中使用,所以现在查询生成器看起来像
Video::find()
->published()
->search($search)
->select(['*',
new yiidbExpression('MATCH(title, description, tags) AGAINST(:search) AS value',['search' => $search])
])
->orderBy('value');
Soution是params方法:
$this->select(['*','MATCH(title, description, tags) AGAINST(:search) AS score'])
->andWhere('MATCH(title, description, tags) AGAINST(:search)', ['search' => $search])
->params(['search' => $search])
->orderBy(['score' => SORT_DESC]);
如果您想使用"值";然后你必须把它写在select语句中。您可以使用";具有";条款
您可以使用以下两种中的任何方法
1.
$query = Product::find()
->andWhere('MATCH ('.Product::tableName().'.name) AGAINST(:q)'
->params(['q' => $this->q])
->orderBy('(MATCH ('.Product::tableName().'.name) AGAINST(:q)) DESC');
2
$query = Product::find();
->select(Product::tableName().'.*, MATCH ('.Product::tableName().'.name) AGAINST(:q) as VL')
->having('VL > 5')
->params(['q' => $this->q]);