關於Thinkphp架構視圖模型調用的一些有關問題總結

來源:互聯網
上載者:User
關於Thinkphp架構視圖模型調用的一些問題總結

對於tp架構中視圖模型的調用在項目中比較常用,這次的畢業設計中對於碰到了一些問題寫下總結:

?

一、自訂DAO的ORM的Model定義在視圖調用時出現異常

?

當把Model定義成形如

class UserModel extends Model {private $ormObj;/** *  * 建構函式 */function __construct(){$this->ormObj=M('User');}}

然後是視圖模型的定義:

class MentionviewModel extends ViewModel {    public $viewFields = array(       'Mention'=>array('id','tid','uid'),       'Topic'  =>  array('create_time','from'=>'topic_from','content','status','_on'=>'Mention.tid=Topic.id'),       'User'  =>  array('nickname','homepage','avatar','_on'=>'Topic.uid=User.id')    );    }

而輸出的SQL語句確是:

SELECT Mention.id AS id,Mention.uid AS uid,Mention.tid AS tid,Topic.create_time AS create_time,Topic.from AS topic_from,Topic.content AS content,User.avatar AS avatar,User.nickname AS nickname,User.homepage AS homepage FROM fl_mention Mention JOIN Topic ON Mention.tid=Topic.id JOIN User ON Topic.uid=User.id WHERE Topic.status=1 and Mention.uid=1 ORDER BY Mention.id desc LIMIT 0,20

?對於要取別名的表名丟失了,這種DAO式的ORM調用時在視圖模型中會出現找不到表名的情況。

?

在父類ViewModel中有這樣一個函數,是提取表名的:

public function getTableName()    {        if(empty($this->trueTableName)) {            $tableName = '';            foreach ($this->viewFields as $key=>$view){                // 擷取資料表名稱                $class  =   $key.'Model';                $Model  =  class_exists($class)?new $class():M($key);                $tableName .= $Model->getTableName();                // 表別名定義                $tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key;                // 支援ON 條件定義                $tableName .= !empty($view['_on'])?' ON '.$view['_on']:'';                // 指定JOIN類型 例如 RIGHT INNER LEFT 下一個表有效                $type = !empty($view['_type'])?$view['_type']:'';                $tableName   .= ' '.strtoupper($type).' JOIN ';                $len  =  strlen($type.'_JOIN ');            }            $tableName = substr($tableName,0,-$len);            $this->trueTableName    =   $tableName;        }        return $this->trueTableName;    }

這裡函數看到會去調用該類的超類Model的 $Model->getTableName() 這個函數:

?

public function getTableName()    {        if(empty($this->trueTableName)) {            $tableName  = !empty($this->tablePrefix) ? $this->tablePrefix : '';            if(!empty($this->tableName)) {                $tableName .= $this->tableName;            }else{                $tableName .= parse_name($this->name);            }            $tableName .= !empty($this->tableSuffix) ? $this->tableSuffix : '';            if(!empty($this->dbName))                $tableName    =  $this->dbName.'.'.$tableName;            $this->trueTableName    =   strtolower($tableName);        }        return $this->trueTableName;    }

這個函數中這個語句empty($this->trueTableName)便是提取表名的

下面給出解決方案一:

class UserModel extends Model {protected $trueTableName = 'fl_user';  private $ormObj;/** *  * 建構函式 */function __construct(){$this->ormObj=M('User');}}

?在該類中加入protected $trueTableName = 'fl_user'; 這個屬性使觸發getTablename函數時可以找到對應的表名;

解決方案二:

function __construct(){parent::__construct();$this->ormObj=M('User');}

?在子類中將覆蓋掉的父類建構函式重新引入

?

?

?

?

二、自串連表的視圖模型調用:

?

形如:

class TopicviewModel extends ViewModel {    public $viewFields = array(       'topic'=>array('id'=>'root_id','content'=>'root_content'),       'Topic'  =>array('id'=>'topic_id','create_time','from'=>'topic_from','content','status','_on'=>'topic.id=topic.rootid')          );    }

上面的語句執行的sql如下:

SELECT topic.id AS root_id,Topic.id AS topic_id FROM fl_topic topic JOIN fl_topic Topic ON topic.id=Topic.rootid

這句sql語句的錯誤很明顯:因為sql是不區分大小寫,所以會直接報??Not unique table/alias: 'Topic'的錯誤。

?

繼續來看這個函數:

 public function getTableName()    {        if(empty($this->trueTableName)) {            $tableName = '';            foreach ($this->viewFields as $key=>$view){                // 擷取資料表名稱                $class  =   $key.'Model';                $Model  =  class_exists($class)?new $class():M($key);                $tableName .= $Model->getTableName();                // 表別名定義                $tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key;                // 支援ON 條件定義                $tableName .= !empty($view['_on'])?' ON '.$view['_on']:'';                // 指定JOIN類型 例如 RIGHT INNER LEFT 下一個表有效                $type = !empty($view['_type'])?$view['_type']:'';                $tableName   .= ' '.strtoupper($type).' JOIN ';                $len  =  strlen($type.'_JOIN ');            }            $tableName = substr($tableName,0,-$len);            $this->trueTableName    =   $tableName;        }        return $this->trueTableName;    }

上面的函數對於前面的‘topic’索引只是做了工廠方式的模型產生。而其中的class_exists是不區分大小寫,而數組的索引是區分大小寫,我們可以利用這個特性,把同一個表的引用用僅大小寫不同的索引表示

再在後面跟上_as屬性即可:

?

下面代碼:

public $viewFields = array(       'topic'=>array('id'=>'root_id','content'=>'root_content','_as'=>'root_topic'),       'Topic'  =>  array('id'=>'topic_id','create_time','from'=>'topic_from','content','status','_on'=>'root_topic.id=topic.rootid')    );

?這樣便可得到正確的sql語句了

SELECT root_topic.id AS root_id,Topic.id AS topic_id FROM fl_topic root_topic JOIN fl_topic Topic ON root_topic.id=topic.rootid

?

tp的確是國內一款少有的成熟的架構~~但有些地方還是要用些另類的技巧來使用,自串連表的視圖模型使用總覺得還是比較尷尬的,期待有更好的方式可以達到自串連的目的

?

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.