Рубрики
Uncategorized

Демонстрация с подключением к нескольким столам с использованием модели под Yii

Автор оригинала: David Wong.

Если вы посмотрите на это хорошо, вы можете перепечатать его и написать происхождение статьи. Если вы не умеете хорошо писать, вы можете критиковать.

Для иллюстрации, это не сложный вопрос, но ответы, данные в Интернете, не очень правильные или не очень полезные. Я написал демо-версию аннотации, которая может облегчить работу каждого. После загрузки, пожалуйста, поместите файлы в модели и контроллеры в модели и контроллеры yii соответственно, а затем выполните sql. Файлы SQL в базе данных.

модели

php
/*
   +----------------------------------------------------------------------+
   | This is a form for employee information. The main table is information about employees. A kind of
   | The supplementary table includes the detailed list of employee types and the detailed list of the departments to which the employees belong.|
   +----------------------------------------------------------------------+
   | Authors: Peace Lao San < [email protected]>.|
   +----------------------------------------------------------------------+
 */

class Staff extends CActiveRecord{
    public static function model($className=__CLASS__){
        return parent::model($className);
    }
    public function tableName(){
        Return'p3_staff'; // name of main table
    }
    public function rule(){
        
    }
    /* relations method*/
    public function relations(){ 
        return array(  
            /*
               +----------------------------------------------------------------------+
               | Explain'type'=> array (self:: BELONGS_TO,'Type','type_id')|
               | 1. Type: You can pick up a name that you remember and use it when connecting multiple tables below.|
               | 2. self:: BELONGS_TO is a connection mode representing many-to-one|
               | 3. Type: The file name of the class to which the linked table belongs, for example/|
               | I want to connect the type table, so I need to create a new table pointer in xxx. PHP under the model./|   
               | This table| 
               | 4. type_id: is the foreign key name of the main table|
               +----------------------------------------------------------------------+
             */
            'type'=>array(self::BELONGS_TO, 'Type', 'type_id'), 
            // If you want to connect more tables, copy the data from the above type, for example
            'depart'=>array(self::BELONGS_TO, 'Depart', 'depart_id'), 
        );
    } 
    /**
     * [getList joins multiple tables and retrieves data]
     *@ return [array] [returns data after joining multiple tables]
     */
    public function getList(){
        $criteria = new CDbCriteria; 
        $criteria->alias = 't';
        $criteria - > with = array ('type','depart'); and // array fills in the key values of the array returned by relations and separates them by
        $result = Staff::model()->with('type','depart')->findAll($criteria);
        $pageInfo = [];
        foreach ($result as $key=>$value) {
            $pageInfo[$key]['id'] = $value['id'];
            $pageInfo[$key]['name'] = $value['name'];
            $pageInfo[$key]['type_id'] = $value['type_id'];
            $pageInfo[$key]['depart_id'] = $value['depart_id'];
            $pageInfo [$key]['type_title']= $value - > type - > title; /// Note that the side table needs to be written like this
            $pageInfo[$key]['depart_title'] = $value->depart->title;
        }
        return $pageInfo;
    } 
}

Вызванный контроллер

· · ·

    $result = Staff::model()->getList();
    echo "
"; print_r($result);

· · ·

Мы можем видеть результат.

Array
(
    [0] => Array
        (
            [id] => 1
            [name]=> his mother
            [type_id] => 1
            [depart_id] => 2
            [type_title]=> Melon eaters who don't know the truth - Type 1
            [depart_title]=> departmental 2
        )
    ......

Адрес для загрузки демо-версии Пароль: h852

Описание ссылки

Оригинал: “https://developpaper.com/demo-with-multi-table-connection-using-model-under-yii/”