现在插件基本弄好了,现在开始做模型,首先新建一个数据:school
CREATE TABLE IF NOT EXISTS `school` ( `id` int(8) NOT NULL, `title` varchar(128) NOT NULL DEFAULT '' COMMENT '标题', `subtitle` varchar(255) NOT NULL DEFAULT '' COMMENT '副标题', `ico` varchar(500) DEFAULT NULL COMMENT '缩略图', `pico` varchar(500) DEFAULT NULL COMMENT '大图', `short_description` varchar(500) NOT NULL DEFAULT '' COMMENT '简短介绍', `content` text DEFAULT NULL COMMENT '内容', `seo_title` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo标题', `seo_keywords` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo关键字', `seo_description` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo描述', `is_top` tinyint(2) NOT NULL DEFAULT 0 COMMENT '是否置顶 1是,0否', `is_rec` tinyint(2) NOT NULL DEFAULT 0 COMMENT '是否推荐:1是,0否', `is_show` tinyint(2) NOT NULL DEFAULT 1 COMMENT '是否显示 1是,0否', `view_count` int(11) NOT NULL DEFAULT 0 COMMENT '观看次数', `sort` smallint(3) NOT NULL DEFAULT 255 COMMENT '排序', `published_at` timestamp NULL DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, `deleted_at` timestamp NULL DEFAULT NULL ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='学校表';
首先新建模型目录:Models 新建 School.php 模型文件:
<?php namespace Addons\School\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class School extends Model { use SoftDeletes; protected $table = 'news'; protected $fillable = ['title','subtitle','ico','pico','short_description','content','seo_title','seo_keywords','seo_description','is_top','is_rec','is_show','sort','published_at','view_count']; protected $hidden = [ 'deleted_at', ]; public function category() { return $this->belongsTo(NewsCategory::class,'category_id'); } /** * 作用域:上线. * * @param $query * * @return mixed */ public function scopePublished($query) { return $query->where('published_at', '<=', date('Y-m-d H:i:s')); } }
因为该项目是分为前端,后端,API端,为了保证能够共有一些接口,使用服务来进行提供:
新建 Service 目录,新建:SchoolService.php 文件
<?php namespace Addons\School\Service; use Addons\School\Models\School; class SchoolService { /** * list */ public function list() { $list = School::get()->toArray(); return $list; } }
在控制器中使用该服务:
<?php namespace Addons\School\Http\Controllers; use Addons\School\Service\SchoolService; class IndexController { protected $schoolService; public function __construct( SchoolService $schoolService ){ $this->schoolService = $schoolService; } /** * index */ public function index() { $list = $this->schoolService->list(); var_dump($list); } }
完整项目目录结构:
就这样开发插件,一个基本的模型查询实例就完成了。