thinkjs 之数据库篇


创建数据库、创建think_user表
  create table think_user (   
 userid varchar(20) not null,   
 username varchar(50) not null,    
passwd varchar(100) not null,   
 photo varchar(255) not null,    
blogurl varchar(255) default null,  
  primary key(userid)
  );
  
建好表后开始编写代码 修改数据库连接配置 目录为app/common/config/db.js
目前本框架支持mysql mongodb  sqlite

建模型
module.exports = Model(function () {
    return {
        getUserList: function () {
            var self = this;
            return self.select().then(function(data) {
                return data;
            });
        }
    };
});
代码如下:
module.exports = Model(function () {
    return {
        getUserList: function () {
            var self = this;
            return self.select().then(function(data) {
                return data;
            });
        }
    };
});
编写控制层
'use strict';
var Base = require('./base.js');
module.exports = think.controller(Base, {
  /**
   * index action
   * @return {Promise} []
   */
  //indexAction: function(self){
  //  //auto render template file index_index.html
  //  return self.display();
  //}
  indexAction: function(){
      var self = this;
      //var userModel = D('user');
    var userModel = this.model("user");
      var userList = userModel.select();
      //将数据库中的值传入userList变量中
      self.assign('userList', userList);
      //渲染到页面上,默认会渲染index_index.html页面
      self.display();
    }
});
显示view 我用了默认的模板
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试功能</title>
<style>
*{padding: 0;margin: 0;font-size: 16px;line-height: 20px;font-family: arial;}
a, a:visited{color:#337ab7;text-decoration: none;}
header{padding: 70px 0 70px 0;background-color: #4A6495}
h1{font-size: 36px;color:#fff;font-weight: normal;}
code{  padding: 2px 4px;font-size: 90%;color: #c7254e;background-color: #f9f2f4;border-radius: 4px;}
.content{width: 1000px;margin: auto}
.wrap{width: 1000px;margin: auto}
.content{margin-top: 80px;}
.list{width: 800px;}
.list .item{position: relative;padding-left: 70px;margin-top: 50px;}
.list .item .step{position: absolute;width: 36px;height: 36px;top:-3px;left:0;border: 5px solid #4A6495;border-radius: 23px;text-align: center;line-height: 36px;}
.list .item h2{font-size: 24px;font-weight: normal;}
.list .item p{line-height: 30px;margin-top: 10px}
</style>
</head>
<body>
  <header>
    <div class="wrap">
      <h1>测试</h1>
    </div>
  </header>
  <div class="content">
    <div class="list">
    <%for(var i=0;i<userList.length;i++){%>
      <div class="item">
        <div class="step"><%=userList[i].userid%></div>
        <h2><%=userList[i].username%></h2>
        <img src="<%-userList[i].photo%>" />
      </div>
      <%}%>
 </div>
</body>
</html>
  启动项目 看效果

  本文源代码: