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