public function actionTestDb() { // return a single user whose ID is 1 // SELECT * FROM `user` WHERE `id` = 1 $user = MyUser::find() ->where(['id' => 1]) ->one(); var_dump($user);echo '<hr/>'; // return the number of users // SELECT COUNT(*) FROM `user` $users = MyUser::find() ->count(); var_dump($users);echo '<hr/>'; // return all users and order them by their IDs // SELECT * FROM `user` ORDER BY `id` $users = MyUser::find() ->orderBy('id') ->all(); var_dump($users); }
yii\db\ActiveRecord::findOne() ? 返回一個活動記錄(Active Record)範例
yi\db\ActiveRecord::findAll() ? 返回 ActiveRecord 的範例陣列
如下範例 ?
public function actionTestDb() { // returns a single customer whose ID is 1 // SELECT * FROM `user` WHERE `id` = 1 $user = MyUser::findOne(1); var_dump($user); // returns customers whose ID is 1,2,3, or 4 // SELECT * FROM `user` WHERE `id` IN (1,2,3,4) $users = MyUser::findAll([1, 2, 3, 4]); var_dump($users); // returns a user whose ID is 5 // SELECT * FROM `user` WHERE `id` = 5 $user = MyUser::findOne([ 'id' => 5 ]); var_dump($user); }
public function actionTestDb() { // insert a new row of data $user = new MyUser(); $user->name = 'MyCustomUser2'; $user->email = '[email protected]'; $user->save(); var_dump($user->attributes); // update an existing row of data $user = MyUser::findOne(['name' => 'MyCustomUser2']); $user->email = '[email protected]'; $user->save(); var_dump($user->attributes); }
呼叫 yii\db\ActiveRecord::delete() 方法
public function actionTestDb() { $user = MyUser::findOne(2); if($user->delete()) { echo "User ID => 2 is deleted"; } }
public function actionTestDb() { MyUser::deleteAll('id >= 20'); }