2016-04-22 99 views
0

我从表中通过javascript获得了一行,并在Productnames控制器中执行了操作。通过javascript在yii2中获取相关模型

我得到的领域,是的productid产品名称bottletype。到目前为止,没关系。

JS

<?php 
$script = <<< JS 
$('#catid').change(function(){ 
    var catid = $(this).val(); 

    $.get('index.php?r=production/productnames/get-for-production',{ catid : catid }, function(data){ 
     alert(data.unitprice); 
     // var data = $.parseJSON(data); 
     // $('#productnames-bottletype').attr('value',data.bottletype) 

    }); 
}); 
JS; 
$this->registerJs($script); 
?> 

ProductnamesController

public function actionGetForProduction($catid) 
    { 
     $bottle = Productnames::findOne(['productnames_productname'=>$catid]); 
     //$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1); 
     echo Json::encode($bottle); 
    } 

行动现在我想从有关产品名称表作为productname.bottletype = bottlename.bottlenamebottlename表中获取数据。

bottlename有3个域:

ID,bottlename,单价。

我越来越产品名称bottlename从上面提到的代码。 W 我想要的帽子是获得单位价格以及上述数据。

下面是截图什么,我现在越来越:

Here

回答

1

你应该有Productnames模型“bottlename”关系“bottlename”表(我称之为bottlenameRelation从bottlename区分场):

public function getBottlenameRelation() { 
     return $this->hasOne(Bottlename::className(), ['bottlename' => 'bottletype']); 
} 

然后在操作添加bottlenameRelation参考:

public function actionGetForProduction($catid) 
{ 
     $bottle = Productnames::find()->with('bottlenameRelation')->where(['productnames_productname'=>$catid])->asArray()->one(); 
     echo Json::encode($bottle); 
} 

输出中的json将包含瓶子关系字段。

为了完整起见,你可以输出JSON这样,也添加正确的HTTP标头:

public function actionGetForProduction($catid) 
{ 
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 
     $bottle = Productnames::find()->with('bottlenameRelation')->where(['productnames_productname'=>$catid])->asArray()->one(); 
    return $bottle; 
} 
+0

它没有显示在输出中的“单价”字段。输出结果与以前相同 – Tanmay

+0

正常工作。非常感谢。 – Tanmay