正文之前想聊一些关于MVC的事情,接触过很多项目,发现很多人还是很自然的把SQL写到Ç层中,整个方法的数据库操作完全没有中号层什么事,可维护性完全为0撒。试想如果有个表要改表名,改字段名,我需要整个项目搜一下都有哪些地方用了这个表。如果产品需要监控某个表的所有操作日志,想想都美滋滋...还是希望大家都注意下,开发不是简单的垒代码,那样没意义,如何让项目变得赏心悦目才是一个优雅的程序员改考虑的。
1.命名规则
定义模型时用名词当类名。因为laravel在模型中没有特殊定义会默认用类名+ s为要操作的表名。如果要自自定义表名,需要在模型中定义:
protected $table ='users';
2.单表查询语句
先拿个比较典型的SQL来举例吧:
select id, title as name from posts where user_id>0 and type =1 and status in (0,1) order by created_at desc
用laravel自带的语句如下:
Post :: select('id','title as name')
-> where([['user_id','>',0],['type',1]])
-> whereIn('status',[0,1])
-> orderBy('created_at','desc')
-> orderBy('id','asc')
->get()
需要注意的是where()第二个参数中不能有in和not in需要用where where,whereNotIn两个函数表达
其中是用和连接,想用或的话需要orWhere,用法与其中一致。
3.多表关联查询语句
照样拿SQL例子说话:
select posts.id, posts.title, count (comments.id) as total_comment, topic_id from posts
LEFT JOIN comments on posts.id = comments.post_id
LEFT JOIN post_topics on posts.id = post_topics.post_id and post_topics.post_id <10000
Where posts.id < 10000 and post_topics.post_id < 100000
Group by posts.id
用laravel自带的语句如下:
Post::select('posts.id', 'posts.title', 'post_topics.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