请帮帮我。
我有桌子:
商品包含字段:
- id int(11)
- name varchar(255)
醇>
订单包含字段:
- id int(11)
- status_id int(2)
醇>
orders_goods 包含字段:
- id int(11)
- order_id int(11)
- good_id int(11)
- 金额 int(5)
醇>
我希望通过 good_id 以及来自同一行的其他字段金额接收订单的所有商品。之后,在视图中,我想以这种格式显示所有订单商品:
- good.name (金额)
- good.name (金额)
- good.name (金额)
现在,在订单模型中,我有一种接收订单商品的方法:
public function getGoods()
{
return $this->hasMany(Goods::className(), ['id' => 'good_id'])->viaTable(
'orders_goods', ['order_id' => 'id'],
function($query) {
return $query->select('*')->from('orders_goods')->where(["order_id" => $this->id]);
}
);
}
在GridView中,我显示了很好的名字:
[
'label' => 'Goods',
'value' => function ($model) {
return implode("\n", ArrayHelper::map($model->goods, 'id', 'name'));
},
],
如何将 amount 字段中的商品数量添加到GridView中的显示?这可以在没有额外的中间模型的情况下完成吗?
"<pre>" . print_r($model->goods, true) . "</pre>"
结果:
<pre>
Array (
[0] => app\models\Goods Object (
[_attributes:yii\db\BaseActiveRecord:private] => Array (
[id] => 1
[name] => Monkey gold
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array (
[id] => 1
[name] => Monkey gold
)
[_related:yii\db\BaseActiveRecord:private] => Array ( )
[_relationsDependencies:yii\db\BaseActiveRecord:private] => Array ( )
[_errors:yii\base\Model:private] =>
[_validators:yii\base\Model:private] =>
[_scenario:yii\base\Model:private] => default
[_events:yii\base\Component:private] => Array ( )
[_eventWildcards:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] => Array ( )
)
[1] => app\models\Goods Object (
[_attributes:yii\db\BaseActiveRecord:private] => Array (
[id] => 2
[name] => Monkey green
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array (
[id] => 2
[name] => Monkey green
)
[_related:yii\db\BaseActiveRecord:private] => Array ( )
[_relationsDependencies:yii\db\BaseActiveRecord:private] => Array ( )
[_errors:yii\base\Model:private] =>
[_validators:yii\base\Model:private] =>
[_scenario:yii\base\Model:private] => default
[_events:yii\base\Component:private] => Array ( )
[_eventWildcards:yii\base\Component:private] => Array ( )
[_behaviors:yii\base\Component:private] => Array ( )
)
)
</pre>
答案 0 :(得分:0)
我问是否可以在不添加中间模型的情况下执行此操作。显然这不可能做到。结果,我这样做:
我在订单模型中添加了模型OrdersGoods,关系hasMany()
:
public function getOrderGoods()
{
return $this->hasMany(OrdersGoods::className(), ['order_id'=> 'id'])->select(['amount']);
}
在GridView中:
[
'label' => 'Goods',
'value' => function ($model) {
$goodsCount = count($model->goods);
$resultValue = "";
for($i=1; $i <= $goodsCount; $i++)
{
$resultValue .= "{$i}) {$model->goods[$i-1]->name} ({$model->orderGoods[$i-1]->amount})\n";
}
return $resultValue;
},
],
写得不是很好,但是有效。谢谢!