On this page
发布文章api
创建相关文件
php
// 创建文章控制器
php think make:controller api/v1/Post
// 创建文章模型
php think make:model Post
// 创建文章验证器
php think make:validate PostValidate
controller层:application\api\controller\v1\Post.php
php
// 发布文章
public function create(){
(new PostValidate())->goCheck('create');
(new PostModel) -> createPost();
return self::showResCodeWithOutData('发布成功');
}
route层:route\route.php
php
// 用户操作(绑定手机)
Route::group('api/:v1/',function(){
...
// 发布文章
Route::post('post/create','api/v1.Post/create');
...
})->middleware(['ApiUserAuth','ApiUserBindPhone','ApiUserStatus']);
validate层:application\common\validate\PostValidate
php
protected $rule = [
'text'=>'require',
'imglist'=>'require|array',
'isopen'=>'require|in:0,1',
'topic_id'=>'require|integer|>:0|isTopicExist',
'post_class_id'=>'require|integer|>:0|isPostClassExist',
];
protected $scene = [
'create'=>['text','imglist','token','isopen','topic_id','post_class_id']
];
BaseValidate层:application\common\validate\BaseValidate
php
// 话题是否存在
protected function isTopicExist($value, $rule='', $data='', $field='')
{
if ($value==0) return true;
if (\app\common\model\Topic::field('id')->find($value)) {
return true;
}
return "该话题已不存在";
}
// 文章分类是否存在
protected function isPostClassExist($value, $rule='', $data='', $field='')
{
if (\app\common\model\PostClass::field('id')->find($value)) {
return true;
}
return "该文章分类已不存在";
}
model层:application\common\model\Post.php
php
// 关联图片表
public function images(){
return $this->belongsToMany('Image','post_image');
}
// 发布文章
public function createPost(){
// 获取所有参数
$params = request()->param();
$userModel = new User();
// 获取用户id
$user_id=request()->userId;
$currentUser = $userModel->get($user_id);
$path = $currentUser->userinfo->path;
// 发布文章
$title = mb_substr($params['text'],0,30);
$post = $this->create([
'user_id'=>$user_id,
'title'=>$title,
'titlepic'=>'',
'content'=>$params['text'],
'path'=>$path ? $path : '未知',
'type'=>0,
'post_class_id'=>$params['post_class_id'],
'share_id'=>0,
'isopen'=>$params['isopen']
]);
// 关联图片
$imglistLength = count($params['imglist']);
if($imglistLength > 0){
$ImageModel = new Image();
$imgidarr = [];
for ($i=0; $i < $imglistLength; $i++) {
if ($ImageModel->isImageExist($params['imglist'][$i]['id'],$user_id)) {
$imgidarr[] = $params['imglist'][$i]['id'];
}
}
// 发布关联
if(count($imgidarr)>0) $post->images()->attach($imgidarr,['create_time'=>time()]);
}
// 返回成功
return true;
}
图片模型:application\common\model\Image.php
php
// 图片是否存在
public function isImageExist($id,$userid){
return $this->where('user_id',$userid)->field('id')->find($id);
}