P
P
Pavel Chaplygin2015-04-15 20:10:28
Yii
Pavel Chaplygin, 2015-04-15 20:10:28

Yii2 ActiveRecord - how to create a relationship through two tables?

The database has sequentially linked tables:
a(id, name)
b(id, a_id, name)
c(id, b_id, name)
d(id, c_id, data)
An AR with links was created for each

class D extends ActiveRecord
{
    public function getC()
    {
        return $this->hasOne(C::className(), ['id' => 'c_id']);
    }
    public function getB()
    {
        return $this->hasOne(B::className(), ['id' => 'b_id'])
            ->via('c');
    }
    public function getA()
    {
        return $this->hasOne(A::className(), ['id' => 'a_id'])
            ->via('b');
    }
}

And in the controller:
$arrData = D::find()
    ->joinWith([
        'c',
        'b',
        'a'
    ])
    ->asArray()
    ->one();

arrData contains only data from tables `b`, `c` and `d`. How to get data from `a`?
PS There is an open issue on the github, but there is no solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-04-15
@butteff

I didn't quite understand the question.
What prevents you from making a selection from a?

use \app\model\a; //a - это наследуемый класс от activeRecord
use \app\model\b; // b - тоже

$id = 21 // известная величина, к примеру, b_id

$bdb = b::findOne(['b_id' => $id]);
$adb = a::findOne(['id' => $bdb->id]);
echo $adb->name

Here is an article from the documentation on working with the database in yii2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question