2016-04-22 14 views
0

Ich bekomme eine Reihe von einer Tabelle durch Javascript und Aktion in Productnames Controller.Holen Sie sich verwandte Modell durch Javascript in yii2

Die Felder Ich bin immer ist productid, Produktname und bottletype. Bis jetzt ist es in Ordnung.

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); 
?> 

Aktion in 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); 
    } 

Jetzt möchte ich Daten erhalten, aus bottlename Tabelle, die zu als productname.bottletype = bottlename.bottlename Produktname Tabelle verwandt ist.

Tabelle bottlename hat drei Felder:

id, bottlename, Einzelpreis.

Ich erhalte Produktname, bottlename von oben erwähnt werden. W Hut Ich möchte ist die Einheitspreis zusammen mit den oben genannten Daten zu bekommen.

Im Folgenden finden Sie einen Screenshot, was ich jetzt immer:

Here

Antwort

1

Sie in Artikelnamen Modell aus bottlename eine ‚bottlename‘ Bezug auf 'bottlename Tisch (ich nenne es bottlenameRelation zu unterscheiden haben sollte Feld):

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

Dann in der Aktion hinzufügen bottlenameRelation Referenz:

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

Der JSON in der Ausgabe enthält Felder für die Beziehung zwischen den Flaschennamen.

Der Vollständigkeit halber, Sie Ausgabe json auf diese Weise könnte, die auch korrekt HTTP-Header hinzufügen:

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

Es ist das „Einzelpreis“ Feld in der Ausgabe nicht angezeigt. Die Ausgabe ist wie früher – Tanmay

+0

funktioniert gut. Vielen, vielen Dank. – Tanmay

Verwandte Themen