我在我的模型类中编写了两个函数,如下所示。
public function fetchByUsername($username)
{
$select=$this->select();
$select->where('username = ?', $username) ;
$user = $this->fetchRow($select);
return $user;
}
public function fetchByPhone($phone)
{
$select = $this->select();
$select->where('phone = ?', $phone) ;
$user = $this->fetchRow($select);
return $user;
}
但我想在我的行表类中编写fetch函数并从模型类访问这些值而不编写上述两个函数。 请帮助我。
由于
user.php的
class Model_User extends Model_DbTable_Row
{
//here i need to write fetch function like below
// public function fetchPhone()
// {
// return $this->phone;
// }
// public function fetchUsername()
// {
// return $this->username;
// }
}
Users.php
class Model_Users extends Model_DbTable_Abstract
{
protected $_name = 'users';
protected $_primary = 'userId';
protected $_rowClass = 'Model_User';
protected $_saveInsertDate = true;
protected $_saveUpdateDate = true;
}
UsersController.php
class Admin_UsersController extends BusinessForum_Admin_Controller
{
public function init()
{
/* Initialize action controller here */
$this->view->pageTitle = 'Users - ' . $this->view->pageTitle;
parent::init();
}
public function indexAction()
{
// get name of the director
$userId = $this->_getParam('directorId');
if ($userId) {
$modelUsers = new Model_Users();
$user = $modelUsers->fetch($userId);
$fullName = $user->firstName." ".$user->lastName;
$directorName = "Direcotor : ".$fullName;
$this->view->directorName = $directorName;
}
}
答案 0 :(得分:1)
public function fetchDetails($attr,$value)
{
$select=$this->select();
if($attr == 'username'){
$select->where('username = ?', $value) ;
else if($attr == 'phone '){
$select->where('phone = ?', $value) ;
}
$user = $this->fetchRow($select);
return $user;
}
并称之为
//user
$details = $your_model->fetchDetails('username',$usernamedata);
//phone
$details = $your_model->fetchDetails('phone',$phonedata);
OR 没有模型功能
$obj = new Yournamespace_Model_Yourfile();
$where = $obj->getAdapter()->quoteInto('username = ?',$username);
$result = $obj->fetchRow($where);
使用模型和使用AND //用于用户名和电话相等
$where = array();
$obj = new Yournamespace_Model_Yourfile();
$where[] = $obj->getAdapter()->quoteInto('username = ?',$username);
$where[] = $obj->getAdapter()->quoteInto('phone = ?',$phone);
$result = $obj->fetchRow($where);
//if you have more than one row then use
$result = $obj->fetchAll($where);
根据OP的请求进行更新
在获取此$result = $obj->fetchRow($where);
您可以获得这些个别元素
$result->phone;
或者
$result->username;
答案 1 :(得分:0)
您可以在表类(public function fetchRow($selectObjet)
)中编写Application_Model_DbTable_TableName
函数。这将覆盖原生fetchRow
方法。您还可以通过调用该函数中的parent::fetchRow
来获取默认结果并修改结果。