Three methods for Yii database operations

Source: Internet
Author: User
This article mainly introduces three methods for Yii to operate databases. For more information, see The PDO method for executing native SQL.

The code is as follows:

$ SQL = ""; // original SQL statement
Xx: model ()-> dbConnection-> createCommand ($ SQL)-> execute ();

II. Active Record mode
(1) New method

The code is as follows:

$ Post = new Post;
$ Post-> title = 'sample post ';
$ Post-> content = 'post body content ';
$ Post-> save ();

(2) Criteria mode
You can also use $ condition to specify more complex query conditions. Without a string, we can make $ condition an instance of CDbCriteria, which allows us to specify conditions not limited to WHERE.

The code is as follows:

$ Criteria = new CDbCriteria;
$ Criteria-> select = 'title'; // select only the 'title' column
$ Criteria-> condition = 'postid =: postid ';
$ Criteria-> params = array (': postid' => 10 );
$ Post = Post: model ()-> find ($ criteria );

One alternative to CDbCriteria is to pass an array to the find method. The keys and values of the array correspond to the attribute names and values of the standard (criterion). the preceding example can be rewritten as follows:

The code is as follows:

$ Post = Post: model ()-> find (array (
'Select' => 'title ',
'Condition' => 'postid =: postid ',
'Params' => array (': postid' => 10 ),

When a query condition is about matching several columns by specified value, we can use findByAttributes (). The $ attributes parameter is an array of values indexed by column names. In some frameworks, this task can be implemented by calling methods similar to findByNameAndTitle. Although this method looks attractive, it often causes confusion, conflicts, and case sensitivity issues such as column names.
III. Query Builder

The code is as follows:

$ User = Yii: app ()-> db-> createCommand ()
-> Select ('Id, username, profile ')
-> From ('tbl _ user u ')
-> Join ('tbl _ profile P', 'U. id = p. user_id ')
-> Where ('Id =: ID', array (': ID' => $ id ))
-> QueryRow ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.