简体   繁体   中英

Yii: Use another table than the model table in FROM with CDbCriteria

How do I change the FROM part of the query when using CDbCriteria? So I can join the main table (of the model) later (News). I need this because the query is much much more efficiënt when joining the main table (News) later with the table Tags. (30 seconds VS 0.125 seconds). Is this possible?

Do I need to create a new CActiveRecord type which extends the object I need (News) but with the other tablename (Tag)?

News and Tags are linked via a linktable NewsTags.

I tried this but it won't work because now it can't map the properties:

<?php

    /**
     * This is the model class for table "news" but with "tag" as tablename
     *
     *  It is a hacky way to use "tag" in FROM of the search query and join later with "news" 
     *  because this is a lot more efficient for searching.
     *  CDbCriteria does not allow to change the FROM table and allways uses the one of the model.
     **/
    class NewsSearchByTagResult extends News
    {

        /**
         * Returns the static model of the specified AR class.
         * @return News the static model class
         */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
         * @return string the associated database table name
         */
        public function tableName()
        {
            return 'tag';
        }

   }
?>

Gives "Property "NewsSearchByTagResult.NewsId" is not defined."

I solved it by splitting it in 2 queries. First getting all the tags with the searchterms and then getting the news with these tags. It's a little bit slower than the preferred solution but it's a lot faster than before. I guess the thing I wanted is impossible.

Now I still need to figure out how to use MATCH...AGAINST with Yii framework because I can't use params and I can't use mysqli_real_escape_string because I don't have access to the db connection... But that's another question...

Blegh I hate ORM's...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM