Laravel study notes (4) model, query

Laravel model read (original)

toArray can be transformed into an array
toSql can see the current query

  1. Reading model of

    App\User::all();                          // 返回包含所有对象的集合
    
    // 以下方法虽然返回的是对象,但是直接可以以数组方式(如:$a[0])取值
    \App\User::where('name', 'John')->first(); // 返回第一条数据的对象
    \App\User::where('id', 1)->value('name');   // 返回name字段的值(string)
     \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
    
  2. where

    where('votes', '=', 100)
    where('votes', 100)
    where('name', 'like', 'T%')
    where([
        ['status', '=', '1'],
        ['subscribed', '<>', '1'],
    ])
    where('votes', '>', 100)->orWhere('name', 'John')    // where votes > 100 or 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。
    
  3. select

    $users = \App\User::select('name', 'email as user_email')->get();
    
    $users = \App\User::distinct()->get();
    // select distinct * from `users1`
    
    $query = \App\User::select('name');
    $users = $query->addSelect('age')->get();
    // select `name`, `age` from `users`
    
    ->selectRaw('department, SUM(price) as total_sales')
    ->groupBy('department')
    ->havingRaw('SUM(price) > ?', [2500])
    ->orderByRaw('updated_at - created_at DESC')
    ->get();
    // select department, SUM(price) as total_sales from `destinations` group by `department` having SUM(price) > 2500 order by updated_at - created_at DESC
    
  4. join

    # inner join
    ->join('contacts', 'users.id', '=', 'contacts.user_id')
    ->select('users.*', 'contacts.phone', 'orders.price')
    ->get();
    // select 'users.*', 'contacts.phone', 'orders.price' from users inner join 'contacts' on 'users.id' =  'contacts.user_id'
    
    # left join
    ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
    ->get();
    
    # right join
    ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
    ->get();
    
    # cross join
    ->crossJoin('colours')
    ->get();
    // 笛卡尔积
    
    # 高级 join
    ->join('contacts', function ($join) {
        $join->on('users.id', '=', 'contacts.user_id')->orOn('users.pid', '=', 'contacts.pid');
    })
    ->get();
    // select * from `users` 
    //     inner join 
    // `contacts` 
    //     on `users`.`id` = `contacts`.`user_id` or `users`.`pid` = `contacts`.`pid`
    
    
    ->join('contacts', function ($join) {
        $join->on('users.id', '=', 'contacts.user_id')
            ->where('contacts.user_id', '>', 5);		 // and `contacts`.`user_id` > 5
    })
    ->get();
    // select * from `users` inner join `contacts` 
    //     on
    // `users`.`id` = `contacts`.`user_id` and `contacts`.`user_id` > 5
    
    
    # union
    $first = App\User::whereNull('first_name');
    
    $users = App\Student::whereNull('last_name')
                ->union($first)
    
                ->get();
    // (select * from `students` where `last_name` is null) union (select * from `users` where `first_name` is null)
    
    # unionAll 和 union 参数一样
    // unionAll 不会去除重复值
    
  5. Sorting, grouping and pagination

    orderBy('name', 'desc')
    
    latest()                // === orderBy('created_at', 'desc')
    
    inRandomOrder()
    // order by RAND()
    
    ->groupBy('account_id')->having('account_id', '>', 100)
    
    ->groupBy('site', 'qianjinyike.com')->having('account_id', '>', 100)
    
    skip(10)->take(5)        // 等价于 offset(10)->limit(5)
    // limit 5 offset 10
    
Published 40 original articles · won praise 0 · Views 789

Guess you like

Origin blog.csdn.net/qj4865/article/details/104137254