2015-03-20 2 views
2

У меня есть 2 модели Onlinelearning и Onlinelearningreviews с отношениями HAS MANY. Я хочу получить конкретный атрибут модели Onlinelearningreviews.Yii2 Получить конкретный атрибут модели отношений

Onlinelearning атрибуты: ID, Title, URL, Description, GradeAge

Onlinelearningreviews атрибуты: ID, OnlinelearningID, Rating, Comments

Модель Onlinelearning:

public function getOnlinelearningreviews() 
{ 
    return $this->hasMany(Onlinelearningreviews::className(), ['OnlineLearningID' => 'ID']); 
} 

Модель Onlinelearningreviews:

public function getOnlineLearning() 
{ 
     return $this->hasOne(Onlinelearning::className(), ['ID' => 'OnlineLearningID']); 
} 

Я хочу получить Title, URL, Description, GradeAge and Rating атрибутов.

следующие работы:

Onlinelearning::find()->select(['Title','URL','Description','GradeAge'])->with('onlinelearningreviews')->asArray()->all(); 

Но когда я указываю рейтинг он дает мне ошибку

Onlinelearning::find()->select(['Title','URL','Description','GradeAge','onlinelearningreviews.Rating'])->with('onlinelearningreviews')->asArray()->all(); 

Как получить только рейтинг атрибут из модели Onlinelearningreviews? Мне не нужны другие атрибуты.

Onlinelearning::find()->with(['onlinelearningreviews'])->asArray()->all() печатает:

Array 
    (
     [0] => Array 
      (
       [ID] => 1 
       [Title] => Udemy 
       [URL] => http://www.google.com 
       [Description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
       [GradeAge] => 2nd to 5th Grade 
       [AddedOn] => 2015-03-20 00:00:00 
       [LastModifiedOn] => 2015-03-20 00:00:00 
       [onlinelearningreviews] => Array 
        (
         [0] => Array 
          (
           [ID] => 1 
           [ParentID] => 1 
           [OnlineLearningID] => 1 
           [Rating] => 3.5 
           [PositiveComments] => It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. . 
           [NegativeComments] => 
           [AddedOn] => 
           [LastModifiedOn] => 
          ) 

         [1] => Array 
          (
           [ID] => 2 
           [ParentID] => 1 
           [OnlineLearningID] => 1 
           [Rating] => 3.5 
           [PositiveComments] => It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. 
           [NegativeComments] => 
           [AddedOn] => 
           [LastModifiedOn] => 
          ) 

        ) 

      ) 
) 

И

Onlinelearning::find() 
     ->select(['Title','URL','Description','GradeAge']) 
     ->with([ 
      'onlinelearningreviews' => function ($query) { 
       /* @var $query yii\db\ActiveQuery */ 

       $query->select('Rating'); 
      }, 
     ]) 
     ->asArray() 
     ->all(); 

печатает:

Array 
(
    [0] => Array 
     (
      [Title] => Udemy 
      [URL] => http://www.google.com 
      [Description] => Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 
      [GradeAge] => 2nd to 5th Grade 
      [onlinelearningreviews] => Array 
       (
       ) 

     ) 
) 
+0

@arogachev: Мне нужны все атрибуты из OnlineLogning и только атрибут Rating от Onlinelearningreviews. Не хотите извлекать ненужный атрибут, который мне не нужен. – Chinmay

+0

Вы хотите, чтобы средняя оценка или все оценки? ... – soju

+0

@soju: Мне нужны все рейтинги – Chinmay

ответ

6

Возможно так:

Onlinelearning::find() 
    ->select(['Title','URL','Description','GradeAge']) 
    ->with([ 
     'onlinelearningreviews' => function ($query) { 
      /* @var $query \yii\db\ActiveQuery */ 

      $query->select('Rating'); 
     }, 
    ]) 
    ->asArray() 
    ->all(); 

См. official docs о том, как настроить отношения запросов в with().

И если вы хотите, чтобы выбрать все атрибуты из Onlinelearning модели можно опустить select часть:

->select(['Title','URL','Description','GradeAge']) 

Update:

Похоже, вы должны включать в себя связанные атрибуты в обеих моделях:

->select(['ID', 'Title','URL','Description','GradeAge']) 

и

$query->select(['OnlinelearningID', 'Rating']); 

В противном случае будет выброшено исключение из Undefinex index.

+0

Я пробовал это, но он не работает :( – Chinmay

+0

Покажите ошибку, которую вы получаете. – arogachev

+0

Я не получаю никаких ошибок, но массив пуст. Я добавил вывод к вопросу. – Chinmay

Смежные вопросы