table1 table1 - name field

table 2 table2 - name field

How to display the value of the name of two identical column names from the mysql database?

Controller:

$advert = Advert::model()->findAllBySql('SELECT table1.name, table2.name FROM table1, table2'); $this->render('index', array('model' => $advert)); 

view:

 <?php foreach ($model as $advert){?> //пробовал так не помогает <?php echo $advert->table1.name ?> <?php echo $advert->table2.name ?> <?php } ?> 

    3 answers 3

    You understand that it does not happen in an array of 2 identical keys with different values, just like two identical properties with different values.

     SELECT table1.name AS name_table_1, table2.name AS name_table_2 FROM table1, table2 <?php echo $advert->name_table_1 ?> <?php echo $advert->name_table_2 ?> 

    And read about normalization of databases and about objects in PHP read, since you allowed yourself to write a property name containing a dot

    • The fact is that I did just that, but the error The property "Advert. Name_table_1" is not defined. - DJK

    Try this:

     $advert = Advert::model()->findAllBySql('SELECT table1.name AS t1_name, table2.name FROM table1 AS t2_name, table2.*'); $this->render('index', array('model' => $advert)); <?php foreach ($model as $advert){?> <?php echo $advert->t1_name ?> <?php echo $advert->t2_name ?> <?php } ?> 

      Several options, the easiest of course the one you are going to use. There is nothing complicated in it; you just need to assign an alias to one of the columns.

       $advert = Advert::model()->findAllBySql('SELECT table1.name AS t1_name, table2.name AS t2_name FROM table1, table2'); 

      t1_name and t2_name the names of the aliases that I invented can be completely anything.

      But in the future, look towards the query designer. By the way, you do not have a bundle in the request. Those. logically, table 2 does not refer to table 1 as criteria. And maybe when you try to fulfill the request, there will be an error.