Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get table with references other table in yii2?

Tags:

php

yii2

i have multiple table that join together and i need one query and get all references too !
is that possible in yii2??
get them in hierarchy array ??
How ???

Is it possible to do not use join???

thanks for your help!!!!

sample db

like image 250
Mohsen Avatar asked Oct 22 '15 08:10

Mohsen


2 Answers

If you created the model classes for each table using Gii and selected to create the relations in the generated models, you can do something like the following.

1) In your Countries model just change the method that declares the relationship with Airports like this:

public function getAirports() {
    return $this->hasMany(Airports::className(), ['country_id' => 'id'])->with('airlines');
}

2) When you do the query for the countries and you need to have the related airports, airlines and flightbooked do it like this:

$countries = Countries::find()
    ->where('something = something_else')
    ->with('airports')
    ->with('flightbooked')
    ->all();

This way you will get all the related models populated with way less queries to the database than using lazy-loading.

like image 70
marche Avatar answered Sep 30 '22 02:09

marche


I just wanted to give a small suggestion:

As you are maintaining the relations in the tables and if you have generated your code using Gii, then that will generate the joins for you. You can then access any column of any table easily.

But I think UNION may not be an alternative to JOIN.

like image 30
K Arun Singh Avatar answered Sep 30 '22 04:09

K Arun Singh