0

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.

2
  • Can you provide more information about this? I don't quite get it. Where does the query return an integer? After save()? And what are you trying to do here? Commented Sep 26, 2016 at 17:33
  • What are you doing ? Executing $query ,saving $model and using $query Commented Sep 26, 2016 at 17:33

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I do not want to return the column but the integer value it has, I'm sorry but I'm a beginner.
@saba ..the first column ..(in you case the only column) is exactly the integer for id_citta ..(alias is the value you stored in citta.citta_id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.