ThinkJS入门学习实例(3)

完整示例代码

五、数据库增删查改

  • 5.1. 查询

首先,我们把think_brand的所有信息显示到首页home/index/index:

View:

<table id="table" cellspacing="0" width="100%">
 <thead>
 <tr>
 <% if(isLogin){ %>
 <th>*</th>
 <% } %>
 <th>Name</th>
 <th>Price</th>
 </tr>
 </thead>
 <tbody>
 <% brand.forEach(function(item) { %>
 <tr>
 <% if(isLogin){ %>
 <td><a href="/admin/index/update?id=<%= item.id %>">修改</a> - <a href="/admin/index/del?id=<%= item.id %>">删除</a></td>
 <% } %>
 <td><a target="_blank" href="<%= item.url %>"><%= item.name %></a></td>
 <td><img src="/upload/<%= item.img %>" alt="<%= item.name %>"/></td>
 </tr>
 <% }); %>
 </tbody>
</table>

Controller:

App/Lib/Controller/Home/IndexController.js

//首页
indexAction: function () {
 //获取登录信息
 var userInfo = this.userInfo;
 var self = this;
 if (!isEmpty(userInfo)) {
 var brandModel = D('Brand');
 var brandData = [];
 //将用户信息赋值到模版变量里,供模版里使用
 brandModel.getBrand().then(function (data) {
 userInfo.name === 'admin' ? brandData = data : brandData = [];
 self.assign({'title': '管理-首页', 'brand': brandData, 'user': userInfo});
 return self.display();
 });
 }
}
  • 5.2. 增加

View:

<form id="add-form" action="/admin/index/addBrand" method="POST" enctype="multipart/form-data">
 <h5>新增品牌</h5>
 <div class="form-group">
 <input class="form-control" type="text" id="name" name="name" placeholder="brand name"/>
 </div>
 <div class="form-group">
 <input type="file" name="img" id="img" placeholder="upload brand image"/>
 </div>
 <div class="form-group">
 <input class="form-control" type="text" id="url" name="url" placeholder="brand url"/>
 </div>
 <button class="btn btn-primary" type="submit">Submit</button>
</form>

因为这里需要上传图片,所以form一定不能漏了enctype属性:multipart/form-data,以保证被发送到服务器的数据不会被编码。

Controller:

//添加
addAction: function() {
 var self = this;
 var where = {
 name: ''
 };
 if (self.isPost()) {
 var brandModel = D('Brand');
 var pData = self.post();
 //获取上传的图片文件
 var vBImg = self.file('img');
 //利用上传图片的name和path属性
 var finalFileName = this.utilUploadImg(pData.name, vBImg.path);
 where.name = pData.name;
 //保存数据到数据库
 pData.img = finalFileName;
 brandModel.thenAdd(pData, where, true).then(function(insertId) {
 if (insertId.type === 'add') {
 return self.redirect('/home/index/index');
 } else {
 return self.error(insertId.type);
 }
 });
 } else {
 self.assign({
 'title': '管理-新增品牌'
 });
 return self.display();
 }
},
//图片上传
utilUploadImg: function(upImgName, upImgPath) {
 var extension = '';
 var finalFileName = '';
 //处理后缀和文件名
 upImgPath.indexOf('png') !== -1 ? extension = '.png' : extension = '.jpg';
 finalFileName = new Date().getTime() + extension;
 //读取文件
 fs.readFile(upImgPath, function(err, data) {
 if (err) {
 console.log('There was an error when reading file');
 } else {
 //写入文件到uplaod
 fs.writeFile('upload/' + finalFileName, data, function(err) {
 if (err) {
 console.log('There was an error when write file');
 } else {
 console.log('saved');
 }
 });
 }
 });
 return finalFileName;
}

上传的图片会被保存到www/upload下,以品牌的name来命名。

注意这里的fs需要先引用node JS fs模块:

var fs = require('fs');
  • 5.3. 删除

Controller:

App/Lib/Controller/Admin/IndexController.js

//删除
delAction: function () {
 var self = this;
 if (self.isGet()) {
 //获取id
 var id = this.get('id');
 D('item').where({id: id}).delete().then(function (affectedRows) {
 if (affectedRows > 0) {
 return self.redirect('index');
 }
 });
 }
}

根据id查找并删除对应项。

  • 5.4. 修改

View

App/View/Admin/index_update.html

<form action="/admin/index/update" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="id" value="<%= brand.id %>"/>
 <div class="form-group">
 <input class="form-control" type="text" name="name" value="<%= brand.name %>"/>
 </div>
 <div class="form-group">
 <input type="file" name="img"/>
 <p class="help-block"><%= brand.img %></p>
 </div>
 <div class="form-group">
 <input class="form-control" type="text" name="url" value="<%= brand.url %>"/>
 </div>
 <button class="btn btn-primary" type="submit">Submit</button>
</form>

Controller:

App/Lib/Controller/Admin/IndexController.js

//修改
updateAction: function() {
 var self = this;
 var id = 0;
 //GET数据
 if (self.isGet()) {
 //获取name值
 id = self.get('id');
 D('Brand').where({
 id: id
 }).find().then(function(theBrand) {
 self.assign({
 'title': '管理-修改',
 'brand': theBrand
 });
 self.display();
 });
 } else if (self.isPost()) {
 //POST数据
 var updateData = self.post();
 var vBImg = self.file('img');
 // 如果没有更改图片, 防止上传空文件
 if (vBImg.originalFilename !== '') {
 var finalFileName = this.utilUploadImg(updateData.name, vBImg.path);
 updateData.img = finalFileName;
 }
 id = self.post('id');
 D('Brand').where({
 id: id
 }).update(updateData).then(function(affectedRows) {
 if (affectedRows > 0) {
 return self.redirect('/home/index/index');
 }
 });
 }
}

根据id查找并修改对应项。

未完待续。。。

更多相关文章

水平有限,如果文章有啥错误,还请不吝赐教 :)

完整示例代码

w3ctech微信

扫码关注w3ctech微信公众号

共收到0条回复

AltStyle によって変換されたページ (->オリジナル) /