K
K
Konstantin Zhikhor2018-02-21 14:26:01
Yii
Konstantin Zhikhor, 2018-02-21 14:26:01

Relationships between tables in Yii2?

Hello, please help me to do the task correctly.
I have a news table which has a sender id. and I need to join it with the users table.
what would happen like this:
5a8d55bb62d0f824377544.png
So that I can display the news and the name of who created it.
And I need it to be in the ListView widget.
here is my additional paper. can you advise me. I hope I made the problem as clear as possible.
Thanks in advance.
Model

<?php

namespace app\models;

use yii\web\UploadedFile;

use Yii;

/**
 * This is the model class for table "news".
 *
 * @property int $id
 * @property string $text
 * @property string $date_create
 * @property int $status
 * @property int $id_user
 * @property string $doc
 *
 * @property Users $user
 */
class News extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'news';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['text', 'date_create', 'id_user'], 'required'],
            [['text'], 'string'],
            [['date_create'], 'safe'],
            [['status', 'id_user'], 'integer'],
            [['doc'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
            [['id_user'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['id_user' => 'id']],
        ];
    }
  
  public function upload()
    {
    die(print_r($this->validate()));
        if ($this->validate()) {
            $this->avatar->saveAs('img/avatars/' . $this->avatar->baseName . '.' . $this->avatar->extension);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'text' => 'Text',
            'date_create' => 'Date Create',
            'status' => 'Status',
            'id_user' => 'Id User',
            'doc' => 'File',
        ];
    }

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

controller and action
public function actionIndex()
    {
    $model = new News();
        $dataProvider = new ActiveDataProvider([
            'query' => News::find(),
      'sort'=>['defaultOrder'=>['id' => SORT_DESC]],
      'pagination' => [
        'pageSize' => 10,
      ],
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'model' => $model,
        ]);
    }

views widget
echo ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_list',
    'summary' => false,
]);

itemView
<div class="news">
  <div class="n_bl">
    <div class="n_bl_1">
      <div class="n_bl_1_1"><a href="/profile"><img src="/web/img/profile.jpg" alt="" class="new_photo"></a></div>
      <div class="n_bl_1_4">	
        <div class="n_bl_1_2"><a href="/profile"></a></div>
        <div class="n_bl_1_3"><?=$model->date_create?></div>
      </div>
    </div>
    <div class="g_g10"><div class="n_bl_1_5" onclick="$('.g_g11').toggleClass('active');"><img src="/web/img/icon/points.svg" alt=""></div>
        <div class="g_g11">
            <ul>
                <li><a href="<?=Url::toRoute(['news/edit','id'=>$model->id])?>">Редактировать</a></li>
                <li><a href="<?=Url::toRoute(['news/delete','id'=>$model->id])?>">Удалить</a></li>
            </ul>
        </div>
        </div>
    
    <div class="n_bl_2">
    <?=Editable::widget(['name'=>'text','inputType'=>'textArea','format' => Editable::FORMAT_BUTTON,'inputType' => Editable::INPUT_TEXTAREA,'asPopover' => true,'value' => $model->text,'header' => '','size'=>'lg']) ?>
    </div>
    <?php if($model->doc): ?>
    <div class="n_bl_3"><img src="/web/img/posd.jpg" width="697" height="156"></div>
    <?php endif; ?>
    <div class="n_bl_4">
      <div class="n_bl_comment">
        <input type="text" placeholder="Напишите комментарий..." class="news_comment">
        <button class="button_news"></button>
      </div>
      <div class="n_bl_like"><div class="like_2"><svg class="like_1" xmlns="http://www.w3.org/2000/svg" viewBox="1248.229 4240.818 19.922 17.41">
  <g id="noun_1232905_cc" transform="translate(1248.229 4240.818)">
    <g id="Group_13" data-name="Group 13" transform="translate(0 0)">
      <path id="Path_6" data-name="Path 6" class="svg-like" d="M19.521,10c-.639,0-2.512,0-4.76,2.887C13.946,11.807,12.293,10,10,10a5.211,5.211,0,0,0-5.2,5.2,5.352,5.352,0,0,0,.375,1.961c.463,1.168,3.041,3.724,6.347,6.942,1.256,1.234,2.358,2.314,2.909,2.931l.331.375.331-.375c.551-.617,1.653-1.675,2.909-2.931,3.306-3.218,5.884-5.8,6.347-6.942a4.934,4.934,0,0,0,.375-1.961A5.211,5.211,0,0,0,19.521,10Zm4.011,6.832c-.441,1.08-3.746,4.3-6.149,6.655-1.058,1.036-2.005,1.961-2.623,2.6-.617-.639-1.565-1.565-2.623-2.6-2.4-2.358-5.708-5.576-6.149-6.655A4.128,4.128,0,0,1,5.682,15.2,4.326,4.326,0,0,1,10,10.882c2.028,0,3.482,1.7,4.408,3l.353.507.353-.507c.926-1.278,2.38-3,4.408-3A4.326,4.326,0,0,1,23.841,15.2,4.055,4.055,0,0,1,23.532,16.832Z" transform="translate(-4.8 -10)"/>
    </g>
  </g>
</svg></div><div class="like_3">123</div></div>
    </div>
  </div>
</div>

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry, 2018-02-21
@shevchenko__k

Good afternoon.
Add a connection to the request for users Model, I think it's redundant to pass to the view. In the view itself, you can get the user's data like this

echo $model->user->name; // подставьте вместо name своё имя поля в таблице user

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question