在thinkphp项目中,如果有订单表,那么你最好不要把订单表的名字设置为order(即使有表前缀),否则当你建立视图模型查询的时候,很可能碰到莫名其妙的查询错误。
下面演示一段由于表名order被当做MySQL的关键字order而导致的错误:
控制器:
class HomeController extends CommonController { public function index(){ $res = D('orderView')->where(array('order.uid'=>11))->order('order.time DESC')->find(); dump($res); } }
<span style="font-size:18px;">class OrderViewModel extends ViewModel{ public $viewFields = array( 'order'=>array('stars'=>'order_stars','_type'=>'LEFT'), 'userinfo'=>array('name','face','_on'=>'order.uid=userinfo.uid','_type'=>'LEFT'), 'history'=>array('comment','_on'=>'order.id=payhistory.oid') ); }</span>
<span style="font-size:18px;">#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN t_userinfo userinfo ON order.uid=userinfo.uid LEFT JOIN t_history hist' at line 1</span>
看看SQL语句
<span style="font-size:18px;">SELECT order.stars AS order_stars,userinfo.name AS name,userinfo.face AS face,history.comment AS comment FROM t_order order LEFT JOIN t_userinfo userinfo ON order.uid=userinfo.uid LEFT JOIN t_history history ON order.id=payhistory.oid WHERE ( order.uid = 11 ) ORDER BY order.time DESC LIMIT 1</span>能注意到:order被当做关键字order来解析了,后面并没有跟by,所以构成了语法错误,不信你可以把order的表名改掉试试,错误就消失了。
解决的办法很简单,在$viewFields里,指定order表的表名为其他表名,比如t_order。
<span style="font-size:18px;">'order'=>array('stars'=>'order_stars','_as'=>'t_order','_type'=>'LEFT'),</span>然后,你的查询条件也需要改一下:
<span style="font-size:18px;">$res = D('orderView')->where(array('t_order.uid'=>11))->order('t_order.time DESC')->find();</span>如此就可以查出正常结果,当然你可以改表名,当你的项目代码已经很多时,不推荐改表名,因为要改的东西比较多,你可能忘记哪些地方的代码需要修改。