警予:使用多个工作表(Yii: working with multiple tables)

2019-09-26 06:41发布

试图执行此查询:

SELECT md.title, md.url 
   FROM MenuData md, Menu m 
   WHERE m.parent=0 
      AND m.menuType=1 
      AND md.menuID = m.id 
  ORDER BY m.sort ASC

如下图所示:

  $criteria = new CDbCriteria();
            $criteria->together = true;
            $criteria->with = array('MenuData');
            $criteria->compare("Menu.menuType", 1);
            $criteria->compare("Menu.parent", 0);
            $criteria->join = 'LEFT JOIN MenuData ON MenuData.menuID=Menu.id';
            $criteria->order = '`Menu.sort` ASC';
            $criteria->compare("MenuData.locale", $this->lang);
            $results = Menu::model()->findAll($criteria);

同时拥有菜单和Menudata模型。 但是,得到以下错误:

Relation "MenuData" is not defined in active record class "Menu". 

Answer 1:

$基准 - >用==加入。

我假设你有你的模型菜单的关系。

 public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'MenuData' => array(self::HAS_MANY, 'Menudata', 'menuID','joinType' => 'LEFT JOIN'),
    );
}

和您的标准:

  $criteria = new CDbCriteria();
        $criteria->together = true;
        $criteria->with = array('MenuData');
        $criteria->compare("t.menuType", 1);
        $criteria->compare("t.parent", 0);
       // $criteria->join = 'LEFT JOIN MenuData ON MenuData.menuID=Menu.id';
        $criteria->order = '`t.sort` ASC';
        $criteria->compare("MenuData.locale", $this->lang);
        $results = Menu::model()->findAll($criteria);


文章来源: Yii: working with multiple tables
标签: php mysql sql yii