创建模型

php artisan make:model User       // 默认对应的表是 users
php artisan make:model AbCd       // 默认对应的表是 ab_cds
/**
规则:
    1. 除第一个大写字母,其他大写字母前都加上下划线
    2. 所有的大写字母改成小写
    3. 末尾加 s
*/

模型之读

App\User::all();                          // 返回包含所有对象的集合
\App\User::where('name', 'John')->first(); // 返回对象
\App\User::where('id', 1)->value('name');   // 返回值,例如 'leon'
\App\User::find(3);                        // 返回主键等于 3 的对象
\App\User::find([1, 2]);                   // 返回主键等于 1 和 2 的对象的集合
\App\User::pluck('age');                   // 返回包含字段值的集合
\App\User::pluck('age', 'id');             // 返回关联集合 id => age,pluck 最多 2 个参数
\App\User::count();                        // 返回记录总数
\App\User::max('id');                      // 返回数字,库没有任何记录返回 null
\App\User::min('id');                      // 返回数字,库没有任何记录返回 null
\App\User::avg('age');                     // 返回数字,库没有任何记录返回 null,同名 averge
\App\User::sum('salary');                  // 返回数字,库没有任何记录返回 0

where

where('votes', '=', 100)
where('votes', 100)
where('votes', '>=', 100)
where('votes', '<>', 100)
where('name', 'like', 'T%')
where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])
where('votes', '>', 100)->orWhere('name', 'John')
whereBetween('votes', [1, 100])           // 包含了 1 和 100
whereNotBetween('votes', [1, 100])
whereIn('id', [1, 2, 3])
whereNotIn('id', [1, 2, 3])
whereNull('last_name')
whereNotNull('updated_at')
whereDate('created_at', '2016-12-31')   // where date(created_at) = '2016-12-31')
whereMonth('created_at', '12')
whereDay('created_at', '31')
whereYear('created_at', '2016')
whereTime('created_at', '=', '11:20:45')
whereColumn('first_name', 'last_name')        // 判断两个字段 相等
whereColumn('updated_at', '>', 'created_at')

whereColumn([
    ['first_name', '=', 'last_name'],
    ['updated_at', '>', 'created_at']
])

where('finalized', 1)->exists();      // 返回 true 或者 false
// select exists(select * from `xxx` where `finalized` = 1) as `exists`
where('finalized', 1)->doesntExist();
// 运行的 SQL 和上面的一样,Laravel 把运行结果取反就达成目的了

where('name', '=', 'John')
->orWhere(function ($query) {  // 传入闭包进 orWhere,避免全局 scope 产生不良影响
    $query->where('votes', '>', 100)
          ->where('title', '<>', 'Admin');
})
// where `name` = John or (`votes` > 100 and `title` <> Admin)

whereExists(function ($query) {
    $query->selectRaw(1)
          ->from('orders')
          ->whereRaw('orders.user_id = users.id');
})   
// where exists ( select 1 from orders where orders.user_id = users.id )

->whereRaw('price > IF(state = "TX", ?, 100)', [200])->get();
// IF 用法:IF(expr1,expr2,expr3)   
// 如果 (expr1 <> 0 and expr1 <> NULL),那么 expr1 就是 true。

标签: none

添加新评论