我们编程一般都是采用mvc的形式,这个想法对我们来说根深蒂固,当我们了解lavarel框架的时候已经被它优雅的编程所折服,那么刚开始我们都会有疑问laravel的model层文件去哪里了,当我们使用PHP artisan make:model privilegeModel(名字随便写,可以不加Model) 创建model 时它默认放在了app同级目录下,也可以自己创建model,只要注意命名空间 就OK!
那么下面我们就开始在创建的model层中开发吧!
创建好model层我们可以使用两种方式
方式一:简单版 使用DB类操作 可以使用自己编写的任意方法
model 层
控制器层加载model
DB类一般操作做:
增加:DB::table('users')->insert(
array('email' => 'john@example.com', 'votes' => 0)
);
建议添加使用 返回自增ID:
$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);
删除:DB::table('users')->where('votes', '<', 100)->delete(); 返回影响行数
修改:DB::table('users')
->where('id', 1)
->update(array('votes' => 1)); 返回影响行数
查询:
1、单条
$data= DB::table('blogs')->where('id',$id)->first();
2、多条
$data= DB::table('blogs')->where("title","官人")->get(); ->where条件可以无限追加
方式二:复杂版采用 Eloquent类(laravel受欢迎的主要原因) 不懂请看:官方文档:https://laravel-china.org/docs/5.1/eloquent-collections
文章:https://lvwenhan.com/laravel/421.html
控制器层加载model 直接User::(操作)
model层
一般操作:
查询:get和all都是返回表中全部对象 加上toArra变成二维数组
User::get()->toArray();
User::all()->toArray();
加上->first() 就是 获取第一条数据
注:转自woshihaiyong168的博客