我正在练习yii1.1。我有两个具有相同功能的模型,如何将它们合并?
class Issue extends TrackStarActiveRecord
...
{
public function getUserText($user_id=null)
{
$sql="SELECT username FROM tbl_user WHERE id= $user_id";
$command = Yii::app()->db->createCommand($sql);
$username = $command->queryAll();
return $username;
}
}
class Project extends TrackStarActiveRecord
{
...
public function getUserText($user_id=null)
{
$sql="SELECT username FROM tbl_user WHERE id= $user_id";
$command = Yii::app()->db->createCommand($sql);
$username = $command->queryAll();
return $username;
}
}
我想从两个不同的视图调用getUserText()函数,但是我不想在两个不同的模型中编写相同的函数。所以我需要合并它们。
答案 0 :(得分:0)
复制代码并在未描述用户的类中获取用户名不是一个好主意。 您可以将方法放在用户类中:
public $id;
public function getUserText()
{
$sql="SELECT username FROM tbl_user WHERE id= $this->id";
$command = Yii::app()->db->createCommand($sql);
$username = $command->queryAll();
return $username;
}
}
并执行它:
$user = new User();
$user->id = 55;
$username = $user->getUserText(); // better call it getName()
另一种方法是使用ActiveRecord,请参阅有关它的Yii文档
答案 1 :(得分:0)
您可以在用户模型中创建静态方法:
class User extends CActiveRecord {
public static function getUserText($id)
{
$sql = "SELECT username FROM tbl_user WHERE id= :id";
$command = Yii::app()->db->createCommand($sql);
return $command->queryAll(true, array(':id' => $id));
}
}
// and call it
$username = User::getUserText(5);