Before the main text, I wanted to talk about MVC. I have been in contact with many projects and found that many people still naturally write SQL into the C layer. The database operation of the whole method has nothing to do with the medium layer, and the maintainability is completely zero. . Just imagine that if there is a table to change the table name and field name, I need to search the entire project to find out where this table is used. If the product needs to monitor all the operation logs of a certain table, think about it. I hope everyone will pay attention to it. Development is not a simple code base, it is meaningless. How to make the project pleasing to the eye is an elegant programmer Considered instead.
1. Naming rules
Use nouns as class names when defining models. Because laravel has no special definition in the model, it will use the class name + s as the table name to be operated by default. If you want to customize the table name, you need to define it in the model:
protected $table = 'users';
2. Single table query statement
Let's take a more typical SQL as an example:
Select `id` from 'posts`, `title` as 'posts` where 'user_id` > 0 and `type` = 1, 'status` in (0,1) and 'status` in (0,1) `created_at` desc, `id` asc
The statement that comes with laravel is as follows:
Post :: select('id','title as name') - > where([['user_id','>',0],['type',1]]) - > whereIn('status',[0,1]) - > orderBy('created_at','id') - > orderBy('id','asc') - > get()方法
It should be noted that there cannot be in and not in in the second parameter of where(), you need to use where where and whereNotIn two functions to express
Among them is use and connection, if you want to use or you need orWhere, and the usage is consistent with it.
3. Multi-table association query statement
Still take the SQL example to speak:
Select posts.id, posts.title, count(comments.id) from posts as total_comment, topic_id leave a JOIN comment on posts.id = comments.post_id on posts.id = post_topics.post_id and post_topics.post_id < 10000 Join post_topics after joining where posts.id < 10000 and post_topics.post_id < 100000 group by posts.id
The statement that comes with laravel is as follows:
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()
If this error is reported: SQLSTATE[42000]: Syntax error or access violation: 1055 'lavarel.posts.title' isn't in GROUP BY. . .
This is because strict mode is turned on in the mysql configuration file, you need to change strict to true in config/database.php