laravel之路-4 数据库操作(查询构造器)

    正文之前想聊一些关于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







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值