如何使用 Yii 中带有 ID 列表的字段中的 ID 从数据库 table 获取所有行?
How to get all rows from database table using ID from field with list of IDs in Yii?
我正在使用 PHP、Yii 1.1 和 MySql 来做一个项目。
我有一个 table products
字段 product_id
, product_category_id
, product_name
, product_image
, product_description
,等等...
product_id
是主键,product_category_id
是商品所属分类的ID(可以取多个id如"1,3,4"为一个字符串) .
如何从 table 中获取所有行,其 product_category_id
包含特定值?
例如,如果 table 是这样的:
| product_id | product_category_id |....
| 1 | 1,3,4 |....
| 2 | 2,5 |....
| 3 | 2,3,6 |....
并且我需要所有行 product_category_id=3
,那么它应该会找到第一行和第三行。
注意:这与
的功能相反
SELECT * FROM `product` WHERE `product_category_id` IN (1,2,3);
在Mysql中使用GROUP_CONCAT(); table 中的所有行添加到一行中;
您需要使用find_in_set()
功能。 Yii 2.0 示例:
$products = Product::find()
->andWhere(new Expresssion('FIND_IN_SET(:category_id, product_category_id)', [
':category_id' => $categoryId,
]))
->all();
Yii 1.1 示例:
$products = Product::model()
->findAll('FIND_IN_SET(:category_id, product_category_id)', [
':category_id' => $categoryId,
]);
FIND_IN_SET(str,strlist)
Returns a value in the range of 1
to N
if the string str
is in the string list strlist
consisting of N
substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of type SET
, the FIND_IN_SET()
function is optimized to use bit arithmetic. Returns 0
if str
is not in strlist
or if strlist
is the empty string. Returns NULL
if either argument is NULL
. This function does not work properly if the first argument contains a comma (,
) character.
我正在使用 PHP、Yii 1.1 和 MySql 来做一个项目。
我有一个 table products
字段 product_id
, product_category_id
, product_name
, product_image
, product_description
,等等...
product_id
是主键,product_category_id
是商品所属分类的ID(可以取多个id如"1,3,4"为一个字符串) .
如何从 table 中获取所有行,其 product_category_id
包含特定值?
例如,如果 table 是这样的:
| product_id | product_category_id |....
| 1 | 1,3,4 |....
| 2 | 2,5 |....
| 3 | 2,3,6 |....
并且我需要所有行 product_category_id=3
,那么它应该会找到第一行和第三行。
注意:这与
的功能相反SELECT * FROM `product` WHERE `product_category_id` IN (1,2,3);
在Mysql中使用GROUP_CONCAT(); table 中的所有行添加到一行中;
您需要使用find_in_set()
功能。 Yii 2.0 示例:
$products = Product::find()
->andWhere(new Expresssion('FIND_IN_SET(:category_id, product_category_id)', [
':category_id' => $categoryId,
]))
->all();
Yii 1.1 示例:
$products = Product::model()
->findAll('FIND_IN_SET(:category_id, product_category_id)', [
':category_id' => $categoryId,
]);
FIND_IN_SET(str,strlist)
Returns a value in the range of
1
toN
if the stringstr
is in the string liststrlist
consisting ofN
substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of typeSET
, theFIND_IN_SET()
function is optimized to use bit arithmetic. Returns0
ifstr
is not instrlist
or ifstrlist
is the empty string. ReturnsNULL
if either argument isNULL
. This function does not work properly if the first argument contains a comma (,
) character.