За последние 24 часа нас посетили 22518 программистов и 1001 робот. Сейчас ищут 759 программистов ...

Getting unknown property: app\models\Comment::profile

Тема в разделе "Yii", создана пользователем roswww, 10 янв 2019.

  1. roswww

    roswww Активный пользователь

    С нами с:
    15 окт 2016
    Сообщения:
    154
    Симпатии:
    4
    Адрес:
    Cтаврополь
    Доброго времени ..
    ..
    У меня в Б/Д в таблицe *user* есть cтолбец *photo* такой код позволяет добавлять в комментарии автора- файлы img .

    Код (Text):
    1. public function saveComment($article_id)
    2.     {
    3.         $comment = new Comment;
    4.         $comment->text = $this->comment;
    5.         $comment->user_id = Yii::$app->user->id;
    6.         $comment->article_id = $article_id;
    7.         $comment->status = 1; //подтверждение коммента 0
    8.         $comment->user->photo;
    9.     //  $comment->profile->avatar();        
    10.         $comment->date = date('Y-m-d');
    11.    
    12.     return $comment->save();
    13.  
    14.     }
    view
    Код (Text):
    1.    <div class="comment-img">
    2.                 <img width="100" class="img-circle" src="<?//= $comment->profile->avatar; ?>" alt="">
    3.                 <img width="100" class="img-circle" src="<?= $comment->user->photo; ?>" alt="">
    4.             </div>
    Также есть таблица *profile* cтолбец *avatar*
    Я пытаюсь перенаправить запрос так: -(раскомментировав выше указанный код)-то есть чтобы рнр брал файлы img c таблицы *profile* cтолбец *avatar* и вставлял их в комменты,но получаю следующую ошибку:-
    Getting unknown property: app\models\Comment::profile

    Пытался решить так правил пути - менял алиасы ,namespace
    Вообщем провозился я и решения не нашёл
    Можете помочь , разобрать этот вопрос.

     
  2. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    А что у тебя в модели? И вообще, что, по твоему, делает сия глубокомысленная строка?
     
    villiwalla нравится это.
  3. roswww

    roswww Активный пользователь

    С нами с:
    15 окт 2016
    Сообщения:
    154
    Симпатии:
    4
    Адрес:
    Cтаврополь
    глубокомысленная строка - она просто забирает и всталяет из Б.Д картинки к автору коммента,-
    --- Добавлено ---
    мне нужно чтоб он забирал img с это модели..

    Код (Text):
    1. <?php
    2.  
    3. /**
    4. * @copyright Copyright &copy; Gogodigital Srls
    5. * @company Gogodigital Srls - Wide ICT Solutions
    6. * @website http://www.gogodigital.it
    7. * @github https://github.com/cinghie/yii2-user-extended
    8. * @license GNU GENERAL PUBLIC LICENSE VERSION 3
    9. * @package yii2-user-extended
    10. * @version 0.6.2
    11. */
    12.  
    13. namespace cinghie\userextended\models;
    14.  
    15. use cinghie\traits\EditorTrait;
    16. use dektrium\user\models\Profile as BaseProfile;
    17. use yii\base\Exception;
    18. use yii\base\InvalidParamException;
    19. use yii\db\ActiveQueryInterface;
    20. use yii\web\UploadedFile;
    21. use yii\web\Upload;
    22. use app\models\CommentForm;
    23. use app\models\Comment;
    24. /**
    25. * Class Profile
    26. *
    27. * @property string $imagePath
    28. * @property string $imageUrl
    29. * @property string $socialImage
    30. * @property ActiveQueryInterface $account
    31. * @property Profile $accountAttributes
    32. */
    33. class Profile extends BaseProfile
    34. {
    35.     use EditorTrait;
    36.  
    37.     /**
    38.      * @inheritdoc
    39.      */
    40.     public function scenarios()
    41.     {
    42.         $scenarios = parent::scenarios();
    43.  
    44.         if(\Yii::$app->getModule('userextended')->avatar) {
    45.             $scenarios['create'][]   = 'avatar';
    46.             $scenarios['update'][]   = 'avatar';
    47.             $scenarios['register'][] = 'avatar';
    48.         }
    49.  
    50.         if(\Yii::$app->getModule('userextended')->birthday) {
    51.             $scenarios['create'][]   = 'birthday';
    52.             $scenarios['update'][]   = 'birthday';
    53.             $scenarios['register'][] = 'birthday';
    54.         }
    55.  
    56.         if(\Yii::$app->getModule('userextended')->firstname) {
    57.             $scenarios['create'][]   = 'firstname';
    58.             $scenarios['update'][]   = 'firstname';
    59.             $scenarios['register'][] = 'firstname';
    60.         }
    61.  
    62.         if(\Yii::$app->getModule('userextended')->lastname) {
    63.             $scenarios['create'][]   = 'lastname';
    64.             $scenarios['update'][]   = 'lastname';
    65.             $scenarios['register'][] = 'lastname';
    66.         }
    67.  
    68.         if(\Yii::$app->getModule('userextended')->signature) {
    69.             $scenarios['create'][]   = 'signature';
    70.             $scenarios['update'][]   = 'signature';
    71.             $scenarios['register'][] = 'signature';
    72.         }
    73.  
    74.         return $scenarios;
    75.     }
    76.  
    77.     /**
    78.      * @inheritdoc
    79.      */
    80.     public function rules()
    81.     {
    82.         $rules = parent::rules();
    83.  
    84.         if(\Yii::$app->getModule('userextended')->birthday) {
    85.             $rules['birthdayLength'] = ['birthday', 'date', 'format' => 'yyyy-mm-dd'];
    86.             $rules['birthdayRequired'] = ['birthday', 'required'];
    87.             $rules['birthdayTrim'] = ['birthday', 'trim'];
    88.         }
    89.  
    90.         if(\Yii::$app->getModule('userextended')->firstname) {
    91.             $rules['firstnameLength'] = ['firstname', 'string', 'max' => 255];
    92.             $rules['firstnameRequired'] = ['firstname', 'required'];
    93.             $rules['firstnameTrim'] = ['firstname', 'trim'];
    94.         }
    95.  
    96.         if(\Yii::$app->getModule('userextended')->lastname) {
    97.             $rules['lastnameLength'] = ['lastname', 'string', 'max' => 255];
    98.             $rules['lastnameRequired'] = ['lastname', 'required'];
    99.             $rules['lastnameTrim'] = ['lastname', 'trim'];
    100.         }
    101.  
    102.         if(\Yii::$app->getModule('userextended')->signature) {
    103.             $rules['signatureLength'] = ['signature', 'string'];
    104.             $rules['signatureTrim'] = ['signature', 'trim'];
    105.         }
    106.  
    107.         return $rules;
    108.     }
    109.  
    110.     /**
    111.      * @inheritdoc
    112.      */
    113.     public function attributeLabels()
    114.     {
    115.         return [
    116.             'avatar' => \Yii::t('userextended', 'Avatar'),
    117.             'birthday' => \Yii::t('userextended', 'Birthday'),
    118.             'firstname' => \Yii::t('userextended', 'Firstname'),
    119.             'lastname' => \Yii::t('userextended', 'Lastname'),
    120.             'name' => \Yii::t('userextended', 'Name'),
    121.             'signature' => \Yii::t('userextended', 'Signature'),
    122.         ];
    123.     }
    124.  
    125.     /**
    126.      * Upload file
    127.      *
    128.      * @param string $filePath
    129.      *
    130.      * @return mixed
    131.      * @throws Exception
    132.      */
    133.     public function uploadAvatar($filePath)
    134.     {
    135.         $file = UploadedFile::getInstance($this, 'avatar');
    136.  
    137.         // if no file was uploaded abort the upload
    138.         if ( null === $file ) {
    139.             return false;
    140.         }
    141.  
    142.         // file extension
    143.         $fileExt = $file->extension;
    144.         // purge filename
    145.         $fileName = \Yii::$app->security->generateRandomString();
    146.         // update file->name
    147.         $file->name = $fileName.".{$fileExt}";
    148.         // update avatar field
    149.         $this->avatar = $fileName.".{$fileExt}";
    150.         // save images to imagePath
    151.         $file->saveAs($filePath.$fileName.".{$fileExt}");
    152.  
    153.         return $file;
    154.     }
    155.  
    156.     /**
    157.      * fetch stored image file name with complete path
    158.      *
    159.      * @return string
    160.      * @throws InvalidParamException
    161.      */
    162.     public function getImagePath()
    163.     {
    164.         return $this->avatar ? \Yii::getAlias(\Yii::$app->getModule('userextended')->avatarPath).$this->avatar : null;
    165.     }
    166.  
    167.     /**
    168.      * fetch stored image url
    169.      *
    170.      * @return string
    171.      * @throws InvalidParamException
    172.      */
    173.     public function getImageUrl()
    174.     {
    175.         if ( !$this->avatar && $this->getAccountAttributes() !== null )
    176.         {
    177.             $imageURL = $this->getSocialImage();
    178.  
    179.         } else {
    180.  
    181.             $avatar   = $this->avatar ?: 'default.png';
    182.             $imageURL = \Yii::getAlias(\Yii::$app->getModule('userextended')->avatarURL).$avatar;
    183.         }
    184.  
    185.         return $imageURL;
    186.     }
    187.  
    188.     /**
    189.      * Process deletion of image
    190.      *
    191.      * @param string $avatarOld
    192.      *
    193.      * @return bool
    194.      * @throws InvalidParamException
    195.      */
    196.     public function deleteImage($avatarOld)
    197.     {
    198.         $avatarURL = \Yii::getAlias(\Yii::$app->getModule('userextended')->avatarPath).$avatarOld;
    199.  
    200.         // check if file exists on server
    201.         if (empty($avatarURL) || !file_exists($avatarURL)) {
    202.             return false;
    203.         }
    204.  
    205.         // check if uploaded file can be deleted on server
    206.         if (!unlink($avatarURL)) {
    207.             return false;
    208.         }
    209.  
    210.         // if deletion successful, reset your file attributes
    211.         $this->avatar = null;
    212.  
    213.         return true;
    214.     }
    215.  
    216.     /**
    217.      * Get image form Social
    218.      *
    219.      * @return string
    220.      */
    221.     public function getSocialImage()
    222.     {
    223.         $account  = $this->getAccountAttributes();
    224.  
    225.         switch($account['provider'])
    226.         {
    227.             case 'facebook':
    228.                 /** @var Account $account */
    229.                 $imageURL = 'https://graph.facebook.com/' . $account['client_id'] . '/picture?type=large';
    230.                 break;
    231.             case 'twitter':
    232.                 /** @var Account $account */
    233.                 $imageURL = '';
    234.                 break;
    235.             default:
    236.                 $imageURL = null;
    237.         }
    238.  
    239.         return $imageURL;
    240.     }
    241.  
    242.     /**
    243.      * @return ActiveQueryInterface
    244.      */
    245.     public function getAccount()
    246.     {
    247.         return $this->hasOne($this->module->modelMap['Account'], ['user_id' => 'user_id']);
    248.     }
    249.  
    250.     /**
    251.      * @return Profile []
    252.      */
    253.     public function getAccountAttributes()
    254.     {
    255.         return $this->hasOne($this->module->modelMap['Account'], ['user_id' => 'user_id'])->asArray()->one();
    256.     }
    257.  
    258. }
    --- Добавлено ---
    мне нужно чтоб он забирал img с это модели..
    B.-А что у тебя в модели?
    O.- можно ка кто ястнея задать вопрос,я ведь показал модель при создании темы.
     
  4. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    С какого перепугу она что-то куда-то вставляет? Забирает и выбрасывает на помойку :)
    Ты показал, как ты создаёшь экземпляр модели Comment и сохраняешь его, а модель ты не показал
     
  5. roswww

    roswww Активный пользователь

    С нами с:
    15 окт 2016
    Сообщения:
    154
    Симпатии:
    4
    Адрес:
    Cтаврополь
    вот есть токая модель но она работает с админкой, .
    Может она при делах,..

    Код (Text):
    1. <?php
    2. /**
    3. * Created by PhpStorm.
    4. * User: jessie
    5. * Date: 17.12.18
    6. * Time: 4:34
    7. */
    8. namespace app\models;
    9.  
    10.  
    11. use Yii;
    12. use yii\web\UploadedFile;
    13. use yii\base\Model;
    14.  
    15.  
    16. class ImageUpload extends Model
    17. {
    18.  
    19.     public $image;
    20.  
    21.     public function rules()
    22.     {
    23.         return [
    24.  
    25.             [['image'], 'required'],
    26.             [['image'], 'file', 'extensions' => 'jpg,png,gif']
    27.  
    28.         ];
    29.     }
    30.  
    31.  
    32.     public function uploadFile(UploadedFile $file, $currentImage)
    33.  
    34.     {
    35.         $this->image = $file;
    36.  
    37.         if ($this->validate())
    38.  
    39.         {
    40.  
    41.             $this->deleteCurrentImage($currentImage);
    42.  
    43.             return $this->saveImage();
    44.         }
    45.  
    46.     }
    47.  
    48.     public function getFolder()
    49.     {
    50.  
    51.         return Yii::getAlias('@web') . 'uploads/';
    52.        // return Yii::getAlias('@web') . 'img/users/';
    53.  
    54.     }
    55.  
    56.  
    57.     public function generateFilename()
    58.  
    59.     {
    60.         return strtolower(md5(uniqid($this->image->baseName)) . '.' . $this->image->extension);
    61.  
    62.     }
    63.  
    64.  
    65.     public function deleteCurrentImage($currentImage)
    66.  
    67.     {
    68.  
    69.         if ($this->fileExists($currentImage))
    70.  
    71.         {
    72.  
    73.             unlink($this->getFolder() . $currentImage);
    74.  
    75.         }
    76.  
    77.     }
    78.  
    79.  
    80.     public function fileExists($currentImage)
    81.  
    82.     {
    83.         if (!empty($currentImage) && $currentImage != null)
    84.  
    85.        {
    86.  
    87.             return file_exists($this->getFolder() . $currentImage);
    88.  
    89.         }
    90.  
    91.   }
    92.  
    93.  
    94.     public function saveImage()
    95.  
    96.     {
    97.  
    98.         $filename = $this->generateFilename();
    99.  
    100.         $this->image->saveAs($this->getFolder() . $filename);
    101.  
    102.         return $filename;
    103.     }
    104.  
    105.  
    106. }
     
  6. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    Вообще ноль понимания. Печально.
     
  7. roswww

    roswww Активный пользователь

    С нами с:
    15 окт 2016
    Сообщения:
    154
    Симпатии:
    4
    Адрес:
    Cтаврополь
    да с понимание норм модель рабочия ,он просто не видит в базе profile
    если делать так
    $comment->user->profile->avatar = 'value';
    то получаешь -
    Косвенная модификация перегруженного свойства app \ models \ User :: $ profile не имеет никакого эффекта
     
  8. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    Поменять - поменял, а сохранять кто будет? Автоматом ничего никуда не сохраняется
     
  9. roswww

    roswww Активный пользователь

    С нами с:
    15 окт 2016
    Сообщения:
    154
    Симпатии:
    4
    Адрес:
    Cтаврополь
    в модели профиля реализованна функция
    --- Добавлено ---
    Код (Text):
    1.  public function uploadAvatar($filePath)
    2.     {
    3.         $file = UploadedFile::getInstance($this, 'avatar');
    4.  
    5.         // if no file was uploaded abort the upload
    6.         if ( null === $file ) {
    7.             return false;
    8.         }
    9.  
    10.         // file extension
    11.         $fileExt = $file->extension;
    12.         // purge filename
    13.         $fileName = \Yii::$app->security->generateRandomString();
    14.         // update file->name
    15.         $file->name = $fileName.".{$fileExt}";
    16.         // update avatar field
    17.         $this->avatar = $fileName.".{$fileExt}";
    18.         // save images to imagePath
    19.         $file->saveAs($filePath.$fileName.".{$fileExt}");
    20.  
    21.         return $file;
    22.     }
    23.  
    24.     /**
    25.      * fetch stored image file name with complete path
    26.      *
    27.      * @return string
    28.      * @throws InvalidParamException
    29.      */
    30.     public function getImagePath()
    31.     {
    32.         return $this->avatar ? \Yii::getAlias(\Yii::$app->getModule('userextended')->avatarPath).$this->avatar : null;
    33.     }
    34.  
    35.     /**
    36.      * fetch stored image url
    37.      *
    38.      * @return string
    39.      * @throws InvalidParamException
    40.      */
    41.     public function getImageUrl()
    42.     {
    43.         if ( !$this->avatar && $this->getAccountAttributes() !== null )
    44.         {
    45.             $imageURL = $this->getSocialImage();
    46.  
    47.         } else {
    48.  
    49.             $avatar   = $this->avatar ?: 'default.png';
    50.             $imageURL = \Yii::getAlias(\Yii::$app->getModule('userextended')->avatarURL).$avatar;
    51.         }
    52.  
    53.         return $imageURL;
    54.     }
    55.  
    56.     /**
    57.      * Process deletion of image
    58.      *
    59.      * @param string $avatarOld
    60.      *
    61.      * @return bool
    62.      * @throws InvalidParamException
    63.      */
    64.     public function deleteImage($avatarOld)
    65.     {
    66.         $avatarURL = \Yii::getAlias(\Yii::$app->getModule('userextended')->avatarPath).$avatarOld;
    67.  
    68.         // check if file exists on server
    69.         if (empty($avatarURL) || !file_exists($avatarURL)) {
    70.             return false;
    71.         }
    72.  
    73.         // check if uploaded file can be deleted on server
    74.         if (!unlink($avatarURL)) {
    75.             return false;
    76.         }
    77.  
    78.         // if deletion successful, reset your file attributes
    79.         $this->avatar = null;
    80.  
    81.         return true;
    82.     }
     
  10. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    Эта строка меняет значение, которое находится в оперативе. А чтоб записалось в базу, надо явно вызвать save у profile