0

Всем привет. Прохожу обучение по Yii2 по книге от Bill Keck Yii2 for beginners. Дошел до 11 главы по созданию Backend`a. Делал всё по книге, однако, всё равно умудрился поймать ошибку.

введите сюда описание изображения

Вот код модуля Profile.php

namespace frontend\models;

use Yii;
use yii\db\ActiveRecord;
use common\models\User;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\db\Expression;

/**
 * This is the model class for table "profile".
 *
 * @property string $id
 * @property string $user_id
 * @property string $first_name
 * @property string $last_name
 * @property string $birthdate
 * @property int $gender_id
 * @property string $created_at
 * @property string $updated_at
 *
 * @property Gender $gender
 */
class Profile extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'profile';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'gender_id'], 'required'],
            [['user_id', 'gender_id'], 'integer'],
            [['first_name', 'last_name'], 'string'],
            [['birthdate', 'created_at', 'updated_at'], 'safe'],
            [['gender_id'], 'exist', 'skipOnError' => true, 'targetClass' => Gender::className(), 'targetAttribute' => ['gender_id' => 'id']],
            [['gender_id'],'in', 'range'=>array_keys($this->getGenderList())],
            [['birthdate'], 'date', 'format'=>'php:Y-m-d'],

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'birthdate' => 'Birthdate',
            'gender_id' => 'Gender ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'genderName' => Yii::t('app', 'Gender'),
            'userLink' => Yii::t('app', 'User'),
            //'username' => Yii::t('app', 'User'),
            'profileIdLink' => Yii::t('app', 'Profile'),

        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getGender()
    {
        return $this->hasOne(Gender::className(), ['id' => 'gender_id']);
    }


    /**
    * behaviors
    */
    public function behaviors()
    {
        return [
            'timestamp' => [
            'class' => 'yii\behaviors\TimestampBehavior',
            'attributes' => [
                                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                                ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                            ],
            'value' => new Expression('NOW()'),
                           ],
               ];
    }

    /**
    * @return \yii\db\ActiveQuery
    */
    public function getGenderName() 
    {
        return $this->gender->gender_name;
    }

    /**
    * get list of genders for dropdown
    */
    public static function getGenderList()
    {    
        $droptions = Gender::find()->asArray()->all();
        return ArrayHelper::map($droptions, 'id', 'gender_name'); 
    }

    /**
    * @return \yii\db\ActiveQuery
    */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    /**
    * @get Username
    */
    public function getUsername() 
    {
        return $this->user->username;
    }

    /**
    * @getUserId
    */
    public function getUserId() 
    {
        return $this->user ? $this->user->id : 'none';
    }

    /**
    * @getUserLink
    */
    public function getUserLink() 
    {
        $url = Url::to(['user/view', 'id'=>$this->UserId]); 
        $options = []; 
        return Html::a($this->getUserName(), $url, $options); 
    }

    /**
    * @getProfileLink
    */
    public function getProfileIdLink() 
    {
        $url = Url::to(['profile/update', 'id'=>$this->id]);
        $options = [];
        return Html::a($this->id, $url, $options); 
    }

    public function beforeValidate()
    {
        if ($this->birthdate != null) {

        $new_date_format = date('Y-m-d', strtotime($this->birthdate));
        $this->birthdate = $new_date_format;
        }   

            return parent::beforeValidate();
    }
}

Где я могу найти ошибку?

1
  • Если вы получили ответ на свой вопрос, пожалуйста отметьте его зеленой галкой под стрелками голосования, чтобы другие участники видели что вопрос имеет решение.
    – user218976
    16 июл 2018 в 14:17

2 ответа 2

0

Все просто: у вас в продукте указан пользователь, который отсутствует в таблице пользователей. В методе getUsername он пытается получить поле username из модели, которую пытается выбрать в методе getUser. Очевидно что в таблице user должна быть запись с идентификатором, который указан в поле user_id этой записи в таблице product.

1
  • Спасибо большое zabachok.
    – BrokenCoin
    16 июл 2018 в 14:15
0

Ответ на мой вопрос https://www.yiiframework.com/forum/index.php/topic/76177-help-with-error-trying-to-get-property-of-non-object/

public function getUsername() 
    {
        if($this->user) {
           return $this->user->username;
       }
       return 'User does not exist';
    }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.