Yii2在最后一个链关系中添加条件

Tod*_*kov 3 database yii2

现在我有:

$products = Product::findAll([1,2,3,4]);
foreach ($products as $product){
    $text = $product->part->type->texts;
}
Run Code Online (Sandbox Code Playgroud)

这将返回表中的相关记录Texts.

但是我需要只有1条记录,为此我需要在最后一次连接中再有一个条件type->texts,这在模型中没有定义.它是动态会话变量.

有没有办法做到这一点?

aro*_*hev 10

如果要修改最后一个关系查询以获得附加条件并返回一条记录而不是多条记录,只需更改上一次关系调用,如下所示:

$text = $product->part->type->getTexts()->andWhere(...)->one();
Run Code Online (Sandbox Code Playgroud)

直接关系方法调用返回yii\db\ActiveQuery实例,因此您可以根据需要修改条件.

如果您想在多个地方使用修改后的关系,请为此创建单独的方法:

/**
 * @return yii\db\ActiveQuery
 */
public function getDynamicText()
{
    // Insert link from texts relation similar as in hasMany() and additional condition in andWhere()
    return $this->hasOne(...)->andWhere(...);
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

$text = $product->part->type->dynamicText;
Run Code Online (Sandbox Code Playgroud)