Saba
Saba

Reputation: 115

yii2 query database return integer

they can not return the query result as an integer, because I want to save 'id' of the query.

My Controller

$query = (new \yii\db\Query())
         ->select(['id_citta'])
         ->from('citta')
         ->where(['nome_citta' => 'London'])->one();


         $model->save();
         $viaggio_partenza->id_viaggio = $model->id_viaggio;
         $viaggio_partenza->citta_partenza = $query;
         $viaggio_partenza->save();

any suggestions?

public function actionOffri()
   {

    $model = new Viaggi;
    $viaggio_partenza = new ViaggiPartenza;

if($model->load(Yii::$app->request->post()) && $model->validate() && $viaggio_partenza->load(Yii::$app->request->post())){


$query = (new \yii\db\Query())
         ->select(['id_citta'])
         ->from('citta')
         ->where(['nome_citta' => 'Torino'])->one();


         $model->save();
         $viaggio_partenza->id_viaggio = $model->id_viaggio;
         $viaggio_partenza->citta_partenza = $query;
         $viaggio_partenza->save();


}else {....}

I would like to retrieve "id_citta" using the query and save it as "citta_partenza", recovery in the form a string that corresponds to integer in the database.

Upvotes: 0

Views: 1696

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133390

If you want the single value you should use scalar() and not one()

$query = (new \yii\db\Query())
     ->select(['id_citta'])
     ->from('citta')
     ->where(['nome_citta' => 'London'])->scalar();

Scalar() return the first column of the select.. while one() return the first model (the object related to first row) of the query

or if you need the model

$query = (new \yii\db\Query())
     ->select(['id_citta'])
     ->from('citta')
     ->where(['nome_citta' => 'London'])->one();

then refer to the attribute

   $model->save();
     $viaggio_partenza->id_viaggio = $model->id_viaggio;
     $viaggio_partenza->citta_partenza = $query->id_citta;
     $viaggio_partenza->save();

Upvotes: 2

Related Questions