You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Yii中实现类似Laravel pluck()的功能,获取指定列值为纯数组

在Yii中实现类似Laravel pluck()的功能

嘿,作为Yii新手,你这个问题我刚接触Yii的时候也踩过坑!Laravel的pluck()确实省心,而在Yii 2.x里,对应的方法是column(),正好能帮你拿到想要的纯值数组。

先说说你当前代码的问题:你用了all()方法,它返回的是Coupon_categories模型的对象数组,所以输出才是带coupon_id键的对象集合。要改成纯值数组,只需要把all()换成column()就搞定了。

方法一:保留select语句的写法

$get_coupon_ids = Coupon_categories::find()
    ->select(['coupon_id'])
    ->where(['in', 'category', $category_id])
    ->column();

方法二:更简洁的写法(省略select)

column()方法可以直接接收列名作为参数,所以你甚至不用写select():

$get_coupon_ids = Coupon_categories::find()
    ->where(['in', 'category', $category_id])
    ->column('coupon_id');

这两种写法都会返回你期望的纯值数组:

[13,14,15]

另外补充个小知识,如果是Yii 1.x版本(看你的代码应该是用Yii 2,不过还是提一下),可以用CHtml::listData()实现类似效果:

$models = Coupon_categories::model()->findAll(['in', 'category', $category_id]);
$get_coupon_ids = CHtml::listData($models, 'id', 'coupon_id');

不过Yii 2里已经不推荐这种方式了,用column()更直接高效。

内容的提问来源于stack exchange,提问作者sam curb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:32:47