【问题标题】:How to use yii\base\model : getAttributes() method in Yii?如何使用 yii\base\model : Yii 中的 getAttributes() 方法?
【发布时间】:2016-01-24 16:49:49
【问题描述】:

使用 getAttributes 方法时出现错误:“在非对象上调用成员函数 getAttributes()”。

现在,在我的控制器中:

$notifications = Notifications::return_new()->getAttributes();

var_dump($notifications);

在模型中

public static function return_new(){
return Notifications::find()->where(['is_seen' => 0])->all();   
}

现在,Yii 文档说 getAttribute() 将数组作为参数,所以我尝试过

$notifications = Notifications::return_new()->getAttributes('text'); 

但它仍然存在相同的错误。有什么帮助吗?

这是模型

<?php

namespace frontend\models;

use Yii;

 */
class Notifications extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return 'notifications';
    }

    public function rules()
    {
        return [
            [['created_on', 'user_id', 'text'], 'required'],
            [['user_id'], 'integer'],
            [['created_on'], 'safe'],
            [['text'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'created_on' => 'Created On',
            'user_id' => 'User ID',
            'text' => 'Text',
        ];
    }
    public static function count_new()
    {
    $new = Notifications::find()->where(['is_seen' => 0])->all();
    return count($new);
    }
    public static function return_new(){
    return Notifications::find()->where(['is_seen' => 0])->all();   
    }
    public function return_all(){
    return Notifications::find()->all();
    }
    public static function checkst(){
    return Notifications::find()->where(['id' => 3])->one();
    }

    public function return_by_date () {
        // write something here.
    }
}   

【问题讨论】:

  • 还显示您的通知模型代码的其他部分..请..
  • 我已经发布了答案..

标签: php yii


【解决方案1】:

如果你使用all()你会得到一个模型集合然后你应该参考

 Notifications::return_new()[0]->getAttributes();

否则你可以

 public static function return_new(){
   return Notifications::find()->where(['is_seen' => 0])->one();   
  }

在这种情况下,您可以使用

$notifications = Notifications::return_new()->getAttributes();

【讨论】:

  • 我认为社区也需要这个答案,因为 Yii 文档没有解释它。 :) 也可能是问题 ;) ?
  • 是的...是参考文档相关的常见问题... ....问是否合理..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 2015-01-28
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
相关资源
最近更新 更多