Yii2使用原生查询find_in_set
时间: 2023-07-06 08:07:55 浏览: 129
在 Yii2 中使用原生查询 `find_in_set` 可以通过以下方式实现:
```php
$tags = "tag1,tag2,tag3";
$query = new \yii\db\Query;
$query->select('*')
->from('my_table')
->where("FIND_IN_SET('tag1', tags) OR FIND_IN_SET('tag2', tags) OR FIND_IN_SET('tag3', tags)");
$results = $query->all();
```
这里的 `FIND_IN_SET` 是 MySQL 的一个字符串函数,用于查找某个字符串是否在另一个以逗号分隔的字符串中。在此示例中,我们将 `$tags` 字符串中的标签分别用 `OR` 连接起来作为查询条件,通过 `Query::where()` 方法传递给查询对象。最终,使用 `Query::all()` 方法获取查询结果。
需要注意的是,使用原生查询可能存在安全风险,需要谨慎使用。建议使用 Yii2 提供的 ActiveRecord 功能,可以更加方便地进行查询和数据操作。
相关问题
yii2 case find_in_set when 1 else 0 end
在 Yii2 中,您可以使用 ActiveQuery::where() 方法来构建 SQL 查询。要使用类似于 MySQL 中的 FIND_IN_SET 函数,您可以编写以下代码:
```php
use yii\db\Expression;
$query = YourModel::find()
->where(new Expression('FIND_IN_SET(:value, yourColumn) = 1', [':value' => $value]));
```
这里,我们使用 `yii\db\Expression` 类来编写原始 SQL 表达式。`FIND_IN_SET` 函数返回一个数字,表示在给定字符串列表中是否找到了指定值。如果找到,则返回该值在列表中的位置,否则返回 0。
我们使用 `= 1` 来测试函数结果是否为真,因为非零数字在 PHP 中被认为是 true,而零被认为是 false。
请注意,您需要将 `$value` 替换为要查找的值,并将 `yourColumn` 替换为您要查询的列名。
yii2 case find_in_set when 1 else 0 end 排序
在 Yii2 中使用 `find_in_set` 函数进行排序可以使用以下代码:
```php
$query = MyModel::find()
->orderBy([
"find_in_set($value, column_name) DESC",
"other_column_name ASC",
]);
```
其中,`$value` 是需要查找的值,`column_name` 是需要在其中查找 `$value` 的字段名。`find_in_set` 函数会返回 `$value` 在 `column_name` 中的位置,如果不存在则返回 0。因此,我们可以使用 `find_in_set` 函数进行倒序排序,这样在 `column_name` 中存在 `$value` 的记录会排在前面。
如果需要在 `$value` 不存在于 `column_name` 中的记录中,将这些记录排在前面,可以使用 `when` 函数进行判断,代码如下:
```php
$query = MyModel::find()
->orderBy([
"(case when find_in_set($value, column_name) then 1 else 0 end) DESC",
"other_column_name ASC",
]);
```
这样,`find_in_set` 函数返回 0 的记录会被当作 `false`,返回非 0 的记录会被当作 `true`。通过 `when` 函数进行判断,如果返回 `true`,则会按照逆序排序,否则按照正序排序。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)