A
A
Andrew2018-01-28 17:07:02
Yii
Andrew, 2018-01-28 17:07:02

Yii2: How to correctly get data from several tables and how to work with join correctly?

I read about related data, everything turned out great with this. The only thing is not clear some points.
1) When I build a connection, does it turn out to be an analogue of join? But what is join and joinWith for? Or is it used in ActiveQuery when a model or component needs to query another table using the query builder? And how is it right to work with joins here? This code didn't work without creating a link (Getting unknown property: common\models\lineage\La2Characters::character_subclasses)

$model = La2Characters::find()
            ->leftJoin('character_subclasses', 'characters.obj_Id = character_subclasses.char_obj_id')
            ->where(['>', 'online', '0'])
            ->all();

If I make a connection
public function getCharacter_subclasses(){
        return $this->hasMany(La2CharacterSubclasses::className(), ['char_obj_id' => 'obj_Id'])->all();
    }

I get the data, only in the join there is no sense
2) When I make a connection with another table, then I have access to the second table only through $obj1->obj2, how can I make sure that all the information is in the first object?
3) Either I'm doing something wrong or, again, I didn't fully understand the concept. When I append asArray() in the query itself, access to the associated data is lost.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem, 2018-01-28
@ntzch

1) No, this is not an analogue of a join. A link is a getter for getting an object linked through the AR DB.
2) Well, you can, of course, cheat, but why is it needed at all? AR is good because each object corresponds to a row in the database, and you want to break this and do not understand what the object will contain, which will contain some left data and not work with them in any way.
3) When you write asArray, you don't get AR objects, but arrays. Arrays do not have a getCharacter_subclasses() method, so there is no access to the data.
The with() method provides you with the ability to eager load. Those. you select your AR object already with an associated AR object. And in the future, all calls to this associated object will not require a query to the database to fetch data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question