我有多到多的关系:
Parent(id) <- Link(parent,child,sort) -> Product(sku)我想从父模型中获得产品的排序列表。
在父模型上,我有两个函数:
public function getLinksDown()
{
return $this->hasMany( DBLink::className(), ['parent' => 'id'])
->from(['linksDown' => DBLink::tableName()]);
}
public function getProducts()
{
return $this->hasMany(DBProduct::className(), ['sku' => 'child'])
->from(['products' => DBProduct::tableName()])
->via('linksDown')
->innerJoin(
['linx' => DBLink::tableName()],
'linx.child = products.sku AND linx.parent=:parent',
[':parent' => $this->id]
)
->orderBy(['linx.order' => SORT_ASC]);
}如果我直接给这个关系打电话,它就能正常工作。
$model = Parent::findOne(1234);
$products = $model->products;产品是正确排序的产品列表。
如果该关系作为"with“失败的一部分调用,则$this->id将为null,这意味着不返回任何产品。
Parent::find()->with('products')->all();发布于 2016-03-15 11:34:29
经过多次绞尽脑汁之后,我已经决定了唯一的解决办法,就是放弃许多需要排序的产品列表的多个关系,然后这样做:
$model = Parent::find()->where(['id' => 1234])->with('linksDown.products')->one();并通过linksDown关系引用每个产品,而不是直接从父模型引用。
foreach( $model->linksDown as $link ) {
dosomethingwith($link->product);
}为了使这一工作正常进行,需要将排序应用于linksDown关系:
public function getLinksDown()
{
return $this->hasMany( DBLink::className(), ['parent' => 'id'])
->from(['linksDown' => DBLink::tableName()])
->orderBy([linksDown.order => SORT_ASC]);
}https://stackoverflow.com/questions/35897938
复制相似问题