Hey Marcelo, while the pointer softark gave you is useful, I don’t you can do what you are asking with Yii2. A relation returns an array of objects or an ActiveQuery result, so in order to do what you want you should cycle through those objects and use the corresponding relations with the other elements.
After all, what result / data structure would you expect this "nested relation" to return?
I think you can define a dynamic relation named "getPesquisaPerguntas" like the following:
class Produto extends ActiveRecord
{
...
// get all Perguntas related to the Produto
public function getPerguntas()
{
return $this->hasMany(PesquisaPergunta::className(), ['id' => 'pergunta_id'])
->viaTable('{{%produto_has_pergunta}}', ['produto_id' => 'id']);
}
// get all Perguntas related to the Produto and a specific Pesquisa
public function getPesquisaPerguntas($pesquisa_id)
{
return $this->hasMany(PesquisaPergunta::className(), ['id' => 'pergunta_id'])
->viaTable('{{%produto_has_pergunta}}', ['produto_id' => 'id', 'pesquisa_id' => $pesquisa_id]);
}
...
}
And you can use this dynamic relation like the following:
$pesquisa = Pesquisa::find($pesquisa_id);
foreach($pesquisa->produtos as $produto) {
// all Perguntas related to the current Produto
$perguntas = $produto->perguntas;
foreach($perguntas as $pergunta) {
echo $pergunta->description;
}
// all Perguntas related to the current Produto and the Pesquisa
$pesquisa_perguntas = $produto->getPesquisaPerguntas($pesquisa_id)->all();
foreach($pesquisa_perguntas as $pergunta) {
echo $pergunta->description;
}
}
Sorry, it’s not tested. But I hope you’ll get the concept.