Yii2中如何从数据库表获取数据?求全局通用方法及代码报错排查
Hey there! Let's tackle your Yii2 questions and fix that error you're facing—happy to help a fellow newbie get up to speed.
Yii2 gives you two main, reliable approaches to pull data from your database:
Using ActiveRecord (Recommended for Most Cases)
This is the ORM (Object-Relational Mapping) way, which is cleaner, safer, and leverages Yii2's built-in features like validation, relationships, and caching. First, make sure you have a model class for your category_translation table (usually generated via Gii or manually created in the models folder).
For example, if your model is named CategoryTranslation, you can fetch data like this:
- Get all records as model objects:
$translations = CategoryTranslation::find()->all(); - Get a single record matching a condition:
$translation = CategoryTranslation::find()->where(['category_id' => 5])->one(); - Get records as associative arrays (instead of model objects, useful for API responses):
$translationsArray = CategoryTranslation::find()->asArray()->all();
Using Database Command (For Raw SQL or Complex Queries)
If you need to run raw SQL (for complex joins or performance-critical queries), use the createCommand method—just note the correct Yii2 syntax (we'll fix your error shortly):
$results = Yii::$app->db->createCommand('SELECT * FROM category_translation')->queryAll();
Always use parameter binding to avoid SQL injection when adding dynamic values:
$results = Yii::$app->db->createCommand('SELECT * FROM category_translation WHERE category_id = :id') ->bindValue(':id', 5) ->queryAll();
Absolutely—you can create reusable methods to avoid repeating code across your app. Here are two practical approaches:
Option 1: Create a Helper Component
Make a custom helper class in components/DbHelper.php:
namespace app\components; use Yii; class DbHelper { public static function getAll($tableName) { return Yii::$app->db->createCommand("SELECT * FROM $tableName")->queryAll(); } public static function getOne($tableName, $condition) { return Yii::$app->db->createCommand() ->select('*') ->from($tableName) ->where($condition) ->queryOne(); } }
Then use it anywhere in your app by importing the class:
use app\components\DbHelper; $translations = DbHelper::getAll('category_translation');
Option 2: Extend BaseActiveRecord
If most of your models use similar fetch logic, create a base model class that all your models inherit from:
namespace app\models; use yii\db\ActiveRecord; class BaseModel extends ActiveRecord { public static function getAllRecords() { return static::find()->asArray()->all(); } public static function getRecordByCondition($condition) { return static::find()->where($condition)->one(); } }
Update your CategoryTranslation model to extend BaseModel instead of ActiveRecord, then call:
$translations = CategoryTranslation::getAllRecords();
The root issue with your code is you're using Yii 1.x syntax in Yii 2.x. In Yii2, Yii::app() is replaced with Yii::$app (note the double colon and dollar sign). Your corrected code should be:
$results = Yii::$app->db->createCommand('SELECT * FROM category_translation')->queryAll(); return $results;
If you still get errors after fixing that, try these debug steps:
- Check your database configuration in
config/db.php—ensure the hostname, username, password, and database name are all correct. - Verify that the
category_translationtable actually exists in your database (double-check for typos in the table name). - Use a try-catch block to get the exact error message:
try { $results = Yii::$app->db->createCommand('SELECT * FROM category_translation')->queryAll(); return $results; } catch (\yii\db\Exception $e) { // Print the error to debug var_dump($e->getMessage()); exit; }
This will show you exactly what's wrong—like a missing table, database permission issue, or SQL syntax mistake.
内容的提问来源于stack exchange,提问作者user759235

