如何在 Yii 中使用 yii\base\model : getAttributes() 方法? [英] How to use yii\base\model : getAttributes() method in Yii?

查看:26
本文介绍了如何在 Yii 中使用 yii\base\model : getAttributes() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 getAttributes 方法时遇到错误:在非对象上调用成员函数 getAttributes()".

I get an error while using getAttributes method : "Call to a member function getAttributes() on a non-object".

现在,在我的控制器中:

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

var_dump($notifications);

在模型中

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

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

Now, the Yii docs say that getAttribute() takes an array as a parameter, so I've tried

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

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

but it still persists with the same error. Any help?

这是模型

<?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.
    }
}   

推荐答案

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

If you use all() you obtain a collection of models and then you should refere to

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

否则你可以

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

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

and in this case you can use

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

这篇关于如何在 Yii 中使用 yii\base\model : getAttributes() 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆