How to use yii\\base\\model : getAttributes() meth

2019-08-13 15:40发布

问题:

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

Now, In my Controller:

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

var_dump($notifications);

In model

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

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?

Here is the model

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

回答1:

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

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

otherwise you can

 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();


标签: php yii