模型 application/common/model/Articles.php
<?phpnamespace app\common\model;use think\Model;class Articles extends Model
{//和栏目关联 属于关系 belongsTopublic function cate(){return $this->belongsTo(Cates::class,'cates_id');}}
控制器 application/admin/controller/Article.php
<?phpnamespace app\admin\controller;use app\admin\validate\ArticleValidate;
use app\common\model\Articles;
use think\Controller;
use think\Request;class Article extends Controller
{/*** 显示资源列表** @return \think\Response*/public function index(){$data = model('articles')->paginate(1);/*一对一*//*foreach ($data as $item){dump($item->cate);}*/return view('admin@article/index',compact('data'));}/*** 显示创建资源表单页.** @return \think\Response*/public function create(){//读取栏目$data = db('cates')->select();return view('admin@article/create',compact('data'));}/*** 保存新建的资源** @param \think\Request $request* @return \think\Response*/public function save(Request $request){//收集表单数据$input = $request->post();//验证数据$ret = $this->validate($input,ArticleValidate::class);//失败判断if(true != $ret){return $this->error($ret);}//成功$userinfo = session('admin.user');$input['user_id']=$userinfo['id'];$ret = Articles::create($input);return redirect(url('article/index'));}/*** 显示指定的资源** @param int $id* @return \think\Response*/public function read($id){//}/*** 显示编辑资源表单页.** @param int $id* @return \think\Response*/public function edit($id){//}/*** 保存更新的资源** @param \think\Request $request* @param int $id* @return \think\Response*/public function update(Request $request, $id){//}/*** 删除指定资源** @param int $id* @return \think\Response*/public function delete($id){//}
}
视图 application/admin/view/article/index.html
{foreach $data as $item}<tr><td>{$item.id}</td><td>{$item->cate['cate_name']}</td><td>{$item.title}</td><td><a @click="delart({$item.id})">删除</a></td></tr>
{/foreach}
{extend name="public/base" /}{block name="content"}
<div class="wrapper wrapper-content animated fadeInRight"><div class="row" style="margin-bottom: 10px;"><div class="col-sm-12 text-right"><a href="/admin/art/create" class="btn btn-primary">添加文章</a></div></div><div class="row"><div class="col-sm-12"><div class="ibox float-e-margins"><div class="ibox-content"><table class="table"><thead><tr><th>ID</th><th>栏目</th><th>标题</th><th>操作</th></tr></thead><tbody>{foreach $data as $item}<tr><td>{$item.id}</td><td>{$item->cate['cate_name']}</td><td>{$item.title}</td><td><a href="/admin/art/{$item.id}/edit">修改</a> |<a class="delart" href="/admin/art/{$item.id}">删除</a></td></tr>{/foreach}</tbody></table></div></div><div class="col-sm-12"><div class="dataTables_paginate paging_simple_numbers" id="DataTables_Table_0_paginate">{$data|raw}</div></div></div></div></div>
{/block}{block name="js"}
<script src="/static/vue.js"></script>
<script>$('.delart').click(function () {// 请求地址var url = $(this).attr('href');// 发送ajax$.ajax({url:url,type:'DELETE',success:function (ret) {alert(ret);}})// 取消a标签默认行为return false;});
</script>{/block}