1. 程式人生 > >laravel之路-4 資料庫操作(查詢構造器)

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