正文之前想聊一些关于MVC的事情,接触过很多项目,发现很多人还是很自然的把SQL写到Ç层中,整个方法的数据库操作完全没有中号层什么事,可维护性完全为0撒。试想如果有个表要改表名,改字段名,我需要整个项目搜一下都有哪些地方用了这个表。如果产品需要监控某个表的所有操作日志,想想都美滋滋...还是希望大家都注意下,开发不是简单的垒代码,那样没意义,如何让项目变得赏心悦目才是一个优雅的程序员改考虑的。
1.命名规则
定义模型时用名词当类名。因为laravel在模型中没有特殊定义会默认用类名+ s为要操作的表名。如果要自自定义表名,需要在模型中定义:
受保护的$ table ='users';
2.单表查询语句
先拿个比较典型的SQL来举例吧:
从'posts`中选择`id`,`title`作为'posts`,其中'user_id`> 0和`type` = 1,'status`在(0,1)和'status`中(0,1) `created_at` desc,`id` asc
用laravel自带的语句如下:
Post :: select('id','title as name') - > where([['user_id','>',0],['type',1]]) - > whereIn('status',[0,1]) - > orderBy('created_at','id') - > orderBy('id','asc') - > get()方法
需要注意的是where()第二个参数中不能有in和not in需要用where where,whereNotIn两个函数表达
其中是用和连接,想用或的话需要orWhere,用法与其中一致。
3.多表关联查询语句
照样拿SQL例子说话:
从帖子中选择posts.id,posts.title,count(comments.id)作为total_comment,topic_id 在posts.id = comments.post_id上留下JOIN注释 在posts.id = post_topics.post_id和post_topics.post_id <10000上加入后加入post_topics where posts.id < 10000 and post_topics.post_id < 100000 group by posts.id
用laravel自带的语句如下:
Post::select('posts.id', 'posts.title', 'topic_id', DB::raw('count(comments.id) as total_comment')) ->leftJoin('comments', 'posts.id', '=', 'comments.post_id') ->leftJoin('post_topics', function ($join) { $join->on('posts.id', '=', 'post_topics.post_id') ->where('post_topics.post_id', '<', 100000); }) ->where([['posts.id', '<', 10000], ['post_topics.post_id', '<', 100000]]) ->groupBy('posts.id') ->get()
如果报这个错:SQLSTATE[42000]: Syntax error or access violation: 1055 'lavarel.posts.title' isn't in GROUP BY。。。
这是因为mysql配置文件中开启了严格模式,需要在config / database.php中将strict改为true