Good afternoon! I can not get a sample field from the related table "Clinics". Trying to get this:

public function actionOpinionsjson() { $one = ClinicOpinions::find() ->select(['id', 'text', 'clinic->name']) ->with('clinic') ->asArray() ->all(); \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return $one; } 

Does not work.

And if there is such a code, without conditions, on the displayed fields, then the data from the associated table falls.

 public function actionOpinionsjson() { $one = ClinicOpinions::find() ->with('clinic') ->asArray() ->all(); \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return $one; } 

Thank!

    2 answers 2

    The whole problem was just in your sample, in the select method you transfer data because it will substitute a script into the query, and for example in MySQL there is no such sample clinic->name , use this option:

      public function actionOpinionsjson() { $one = ClinicOpinions::find() ->select(['id', 'text', 'clinic.name']) ->with('clinic') ->asArray() ->all(); \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return $one; } 
    • It doesn't work, Mysql also thinks that Unknown column 'clinic.name' in 'field list' - rud99
    • @ rud99 what kind of query does it generate? - Yaroslav Molchan
    • here, it is clear that the field does not fall into "SELECT id , text , clinic . name FROM clinic_opinions " but the link is public function getClinic () {return $ this-> hasOne (Clinics :: className (), ['id' => 'clinic_id']); } - rud99
    • @ rud99 try to replace with joinWith - Yaroslav Molchan
    • Here is the code for $ one = ClinicOpinions :: find () -> with (['clinic' => function ($ query) {$ query-> select ('name');}]) -> asArray () -> all (); Generates 2 such queries: SELECT * FROM clinic_opinions and SELECT name FROM clinics WHERE id IN ('1', '3') - rud99
     public function actionOpinionsjson() { $one = ClinicOpinions::find() ->select(['id', 'text', 'clinic_id']) ->with(['clinic'=>function($q){ $q->select(['name']) }]) ->asArray() ->all(); \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return $one; } 

    or

     $one = ClinicOpinions::find() ->select(['id', 'text', 'clinic_id', Clinic::tableName().'.name']) ->joinWith('clinic') ->asArray() ->all(); 
    • The code above has already been tried before, it only performs this query: SELECT id , text FROM clinic_opinions - rud99
    • In general, it should generate two requests, it is possible to replace the with joinWith , it should create one - Bookin
    • Hmm, I also forgot something, you need a key for communication, and where do you choose it? True, nowhere, here's the result - no, changed the answer, but then you should already know the connection - Bookin
    • This link is public function getClinic () {return $ this-> hasOne (Clinics :: className (), ['id' => 'clinic_id']); } - rud99
    • changed the answer, check - Bookin