【问题标题】:Output all 'findbyattributes' in yii 1.1在 yii 1.1 中输出所有 'findbyattributes'
【发布时间】:2016-03-14 01:06:14
【问题描述】:

我在 yii 中有一个 findByAttributes,我想知道你如何输出所有符合指定条件的数据

下面有一个例子:

假设在我的Test 表中,我有 3 行在test1 属性中具有值1,那么我的视图中有此代码

$a= Test::model()->findByAttributes(array('test1'=> '1'));
$b= $a-> id;
print_r($b);

我注意到此代码将打印 id '1' 而不是 '1 2 3'。

我可以使用什么代码来输出所有 test1 属性中为 1 的 id?

对不起初学者的问题。我希望任何人都可以帮助...

【问题讨论】:

    标签: php yii find


    【解决方案1】:

    如果您想获取所有记录,您必须使用方法 findAllByAttributes (http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findAllByAttributes-detail) 而不是 findByAttributes。方法 findAllByAttributes 将返回所有满足要求的行,然后您应该对其进行迭代以获取 id。

    例子,

    foreach( $models as $model) { 
        print_r($model->id);
    }
    

    但如果您只想获取 id,最好使用 CDbCommand 和 querycolumn

    Yii::app()->db
    ->createCommand()
    ->select('id')
    ->from('Test')
    ->where('test1=:value', array(':value'=> 1))
    ->queryColumn()
    

    它将返回一个 id 数组

    【讨论】:

    • 我明白了。谢谢你的回答......但是我如何获得一个属性......就像上面的例子一样,我有$b= $a-> id;你能举个例子吗?
    【解决方案2】:

    要检索所有符合特定条件的行,您可以使用

     findAllByAttributes();
    

    为了获得所有结果,你必须循环例如这个结果:

    $a= Test::model()->findAllByAttributes(array('test1'=> '1'));
    
    foreach($a as $key => $value)  {
    
     echo $value->id
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2013-05-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多