R
R
RR2015-03-18 13:28:45
Yii
RR, 2015-03-18 13:28:45

Yii2 / Active Record / How to get fields from Join table?

Actually, the code is:

$data = Media::find()
            ->select( ['media.*', 'content.*'] )
            ->leftJoin('content','`content`.`id` = `media`.`parent_id`')
            ->orderBy(['`media`.`id`' => SORT_DESC])->all();

The Media model itself is inherited from ActiveRecord
. As a result, each element consists of the fields of the media table, and there is no data from the content table that is joined.
Posdkazhite how to pick out these fields?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Novikov, 2015-03-18
@romkaby

I used custom behavior for this. The solution is not the most beautiful, but nothing better came up with. This behavior allows the model to have completely arbitrary properties.
custom Behavior class

namespace app\custom\behaviors;

use yii\base\Behavior;

class ExtraPropsBehaviour extends Behavior
{
  protected $_props = [];

  public function canGetProperty($name, $checkVars = true)
  {
    return TRUE;
  }

  public function canSetProperty($name, $checkVars = true)
  {
    return TRUE;
  }

  public function __get($name)
  {
    return isset($this->_props[$name]) ? $this->_props[$name] : null;
  }

  public function __set($name, $value)
  {
    $this->_props[$name] = $value;
  }

  public function __isset($name)
  {
    return isset($this->_props);
  }

}

and add this to the model
/** @inheritdoc */
  public function behaviors()
  {
    return [
      ExtraPropsBehaviour::className()
    ];
  }

Once applied, you can access the results of the joined table as simple model properties:
$model->field_from_joined_table

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question