Yii: working with multiple tables

2019-07-27 09:57发布

Trying to execute this query:

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

Like below:

  $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);

Have both Menu and Menudata models. But getting following error:

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

标签: php mysql sql yii
1条回答
Summer. ? 凉城
2楼-- · 2019-07-27 10:13

$criteria->with == join.

I assume you have a relation in your model menu.

 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'),
    );
}

And your criteria:

  $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);
查看更多
登录 后发表回答