laravel 操作数据库以及返回值,ORM、DB 方便查看

本文深入讲解了ORM操作的各种技巧,包括但不限于SQL语句的构造、条件筛选、联表查询、数据检索、批量插入、更新与删除操作,以及数据的排序、分页、聚合和缓存策略。文章还介绍了如何使用Eloquent进行Eager Loading、获取数据和执行复杂查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 ORM操作

Eloquent Cheat Sheet

eg1:$result = DB::table('Orders as o')
->join('Stores as s', 's.id', '=', 'o.store_id')
->where('s.admin_id', auth()->user->id)
->get();


Select
  ->select('col1','col2')
  ->select(array('col1','col2'))
  ->select(DB::raw('businesses.*, COUNT(reviews.id) as no_of_ratings, IFNULL(sum(reviews.score),0) as rating'))  
  ->addSelect('col3','col4')
  ->distinct() // distinct select

From
  ->from('table')
  ->from(DB::raw('table, (select @n :=0) dummy'))
  ->from(DB::raw("({$subQuery->toSql()}) T ")->mergeBindings($subQuery->getQuery())

Where
  ->where('column','value')
  ->where(['column'=>'value','column2'=>'value2'])
  ->where('column','LIKE','%'.$value.'%')
  ->where(function ($query) {
    $query->where('a', '=', 1)
        ->orWhere('b', '=', 1);
  })
 ->where(function ($query) use ($a,$b) {
    $query->where('a', '=', $a)
        ->orWhere('b', '=', $b);
  })
  ->orWhere('column','!=', 'value')
  ->whereRaw('age > ? and votes = 100', array(25))

  ->whereRaw(DB::raw("id in (select city_id from addresses GROUP BY addresses.city_id)"))

  ->whereExists(function($query)
  {
    $query->select(DB::raw(1))
        ->from('business_language')
        ->whereRaw('business_language.language_id = languages.id')
        ->groupBy('business_language.language_id')
        ->havingRaw("COUNT(*) > 0");
  })
  ->orWhereExists()
  ->whereNotExists()
  ->orWhereNotExists()

  ->whereIn('column',[1,2,3])
  ->orWhereIn()
  ->whereNotIn('id', function($query){
    $query->select('city_id')
    ->from('addresses')
    ->groupBy('addresses.city_id');
  })
  ->whereNotIn()
  ->orWhereNotIn

  ->whereNull('column') //where `column` is null
  ->orWhereNull('column') //or where `column` is null
  ->whereNotNull('column')  //where `column` is not null 
  ->orWhereNotNull('column')  //or where `column` is not null 

  ->whereDay()
  ->whereMonth('column', '=', 1) //
  ->whereYear('column', '>', 2000) //uses sql YEAR() function on 'column'
  ->whereDate('column', '>', '2000-01-01')
  //->orwhereDate('column', '>', '2000-01-01')   竟然成功了

Joins
  ->join('business_category','business_category.business_id','=','businesses.id')
  ->leftJoin('reviews','reviews.business_id', '=', 'businesses.id')
  ->join('business_category',function($join) use($cats) {
    $join->on('business_category.business_id', '=', 'businesses.id')
    ->on('business_category.id', '=', $cats, 'and', true);
  })
  ->join(DB::raw('(SELECT *, ROUND(AVG(rating),2) avg FROM reviews WHERE rating!=0 GROUP BY item_id ) T' ), function($join){
    $join->on('genre_relation.movie_id', '=', 'T.id')
  })

Eager Loading
  ->with('table1','table2')
  ->with(array('table1','table2','table1.nestedtable3'))
  ->with(array('posts' => function($query) use($name){
    $query->where('title', 'like', '%'.$name.'%')
      ->orderBy('created_at', 'desc');
  }))

Grouping
  ->groupBy('state_id','locality')
  ->havingRaw('count > 1 ')
  ->having('items.name','LIKE',"%$keyword%")
  ->orHavingRaw('brand LIKE ?',array("%$keyword%"))

Cache
  ->remember($minutes)
  ->rememberForever()

Offset & Limit
  ->take(10)
  ->limit(10)
  ->skip(10)
  ->offset(10)
  ->forPage($pageNo, $perPage)

Order
  ->orderBy('id','DESC')
  ->orderBy(DB::raw('RAND()'))
  ->orderByRaw('type = ? , type = ? ', array('published','draft'))
  ->latest() // on 'created_at' column
  ->latest('column')
  ->oldest() // on 'created_at' column
  ->oldest('column')

Create
  ->insert(array('email' => 'john@example.com', 'votes' => 0))
  ->insert(array(   
    array('email' => 'taylor@example.com', 'votes' => 0),
    array('email' => 'dayle@example.com', 'votes' => 0)
  )) //batch insert
  ->insertGetId(array('email' => 'john@example.com', 'votes' => 0)) //insert and return id

Update
  ->update(array('email' => 'john@example.com'))
  ->update(array('column' => DB::raw('NULL')))
  ->increment('column')
  ->decrement('column')
  ->touch() //update timestamp
  ->updateOrCreate([])

Delete
  ->delete()
  ->forceDelete() // when softdeletes enabled
  ->destroy($ids) // delete by array of primary keys
  ->roles()->detach() //delete from pivot table: associated by 'belongsToMany'

Getters
  ->find($id)
  ->find($id, array('col1','col2'))
  ->findOrFail($id)
  ->findMany($ids, $columns)
  ->first(array('col1','col2'))
  ->firstOrFail()
  ->all()
  ->get()
  ->get(array('col1','col2')) 
  ->getFresh() // no caching
  ->getCached() // get cached result
  ->chunk(1000, function($rows){
    $rows->each(function($row){

    });
  })
  ->lists('column') // numeric index
  ->lists('column','id') // 'id' column as index
  ->lists('column')->implode('column', ',') // comma separated values of a column
  ->pluck('column')  //Pluck a single column's value from the first result of a query.
  ->value('column')  //Get a single column's value from the first result of a query.

Paginated results
  ->paginate(10)
  ->paginate(10, array('col1','col2'))
  ->simplePaginate(10)
  ->getPaginationCount() //get total no of records

Aggregate
  ->count()
  ->count('column')
  ->count(DB::raw('distinct column'))
  ->max('rating')
  ->min('rating')
  ->sum('rating')
  ->avg('rating')
  ->aggregate('sum', array('rating')) // use of aggregate functions

Others
  ->toSql() // output sql query
  ->exists() // check if any row exists
  ->fresh() // Return a fresh data for current model from database
确定记录是否存在
  ->doesntExist()   or  ->exists()

Object methods
  ->toArray() //
  ->toJson()
  ->relationsToArray() //Get the model's relationships in array form.
  ->implode('column', ',') // comma separated values of a column
  ->isDirty()
  ->getDirty() //Get the attributes that have been changed but not saved to DB

Debugging 打印sql语句
DB::enableQueryLog();
DB::getQueryLog();
Model::where()->toSql() // output sql query

 

返回值1

DB Facades
$users = DB::table('users')->get(); 返回值:数组结果,其中每一个结果都是 StdClass
$user = DB::table('users')->first(); 返回值:单个 StdClass 实例
 

Eloquent
$user = User::first(); 返回值:Eloquent 对象
$user = User::find(); 返回值:Eloquent 对象
$users = User::get(); 返回值:Eloquent 集合
$users = User::all(); 返回值:Eloquent 集合
$user = User::create($data); 返回值:Eloquent 对象
$user = new User();
$user->name = "admin"
$user->save();
 
返回值:Eloquent 对象
$result = User::insert($data); 返回值:bool
$result = $user->delete(); 返回值:bool
$count = User::destroy([1, 2]); 返回值:删除记录数
$count = User::where('id', '>', 1)->delete(); 返回值:删除记录数
$count = User::where('id', '>', 10)->update(['status' => 1]);返回值:更新记录数
$count = User::where('id', '>', 10)->increment('age', 1); 返回值:更新记录数

返回值2

$results = DB::select('select * from users where id = :id', ['id' => 1]); //return 数组对象
数组对象转数组:json_decode(json_encode($res), true)

DB::insert('insert into users (id, name) values (?, ?)', [1, '学院君']);  //return true  or false

$affected = DB::update('update users set votes = 100 where name = ?', ['学院君']);//返回受更新语句影响的行数

$deleted = DB::delete('delete from users'); //返回被删除的行数


DB::statement('drop table users'); //不返回任何值,比如新增表,修改表,删除表等
$sql_get  = "SELECT `location_id`, `device_id`, `latitude`, `longtitude`, `accuracy`, UNIX_TIMESTAMP(`locate_time`) AS `timestamp` FROM `device_ios_locations` WHERE `device_id`=? AND `locate_time`=FROM_UNIXTIME(?) LIMIT 1";

$res = DB::select( $sql_get, array($device_id, $timestamp) );  //数组对象
$result['data'] = json_decode(json_encode($res), true); //数组
INSERT IGNORE INTO users ( `name`, `email`) VALUES ( 1, 'taylor@example.com');

$result = DB::table('users')->insertOrIgnore([
    ['name' => 1, 'email' => 'taylor@example.com']
]);

$result, 如果已存在 返回 0  不存在返回1

 DB::raw() 

// 所有的原生sql函数都可以用  DB::raw() 去书写
$sql = DB::table('device_ios_photos')->where('photo_id','=',39)->update(['created_at'=>DB::raw('CURRENT_TIMESTAMP')]);

$sql = DB::update('update device_ios_photos set created_at = CURRENT_TIMESTAMP where photo_id = ?', [39]); 

DB

从数据表中取得单一数据列:

<?php
DB::table('users')->where('name', 'John')->first();
从数据表中取得单一数据列的单一字段:

<?php
 
$name = DB::table('users')->where('name','John')->pluck('name');
 
换做Laravel中的写法,先定义好Model
// 芯片记录
$chip_codes = TrGoModel::query()->where('deleted_at', '=', null)->pluck('chip_code');  
从数据表中取得单一字段值的列表:

<?php
 
$roles = DB::table('roles')->lists('title');
 
// 重新命名title值为name
$roles = DB::table('roles')->lists('title','name');
从指定查询子句:

<?php
$users = DB::table('users')->select('name','email')->get();
 
$users = DB::table('users')->distinct()->get();
 
$users = DB::table('users')->select('name as user_name')->get();
 
// 增加查询子句到现有的查询中
$users = DB::table('users')->select('name')->addSelect('age')->get();
where,or的用法:

<?php
$users = DB::table('users')->where('votes', '>', 100)->orWhere('name','John')->get();
 
$users = DB::table('users')->whereBetween('votes',[1,100])->get();
 
$user = DB::table('users')->whereNotBetween('votes',[1,100])->get();
 
$users = DB::table('users')->whereIn('id',[1,2,3])->get();
$users = DB::table('users')->whereNotIn('id',[1,3])->get();
 
$users = DB::table('users')->whereNull('updated_at')->get();
 
$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')->whereIdAndEmail(2, 'john@ss.com')->first();
$jane = DB::table('users')->whereNameOrAge('jane',22)->first();
?>
排序(Order By) 、分群(Group By) 及Having的用法:

<?php
$users = DB::table('users')->orderBy('name','desc')->groupBy('count')->having('count','>',100)->get();
 
// 偏移(offset)及限制Limit
$users = DB::table('users')->skip(10)->table(5)->get(); 
Joins:

<?php
DB::table('users')->join('contacts','users.id','=','contacts.user_id')
->join('orders','users.id','=','orders.user_id')
->select('user.id','contacts.phone','orders.price')
->get();
 
// LEFT JOIN
DB::table('users')->LEFTJoin('posts','users.id','=','posts.user_id')->get();
 
DB::table('users')->join('contacts',function($join){
     $join->on('users.id','=','contacts.user_id')->orOn(...);
})->get();
 
DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();
 

Wheres:

<?php
 
//有些时候你需要更高级的 where 子句,如「where exists」或嵌套的群组化参数。Laravel //的查询构造器也可以处理这样的情况:
 
DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function($query)
            {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();
/*
上面的查找语法会产生下方的 SQL:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
*/
 
//Exists 语法
DB::table('users')
            ->whereExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();
 
/*
上面的查找语法会产生下方的 SQL:
select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)
*/<br><br>whereRaw(可以加原生语句):例如:
TrGoModel::query()->whereRaw('id = 286')->first();
聚合:

$users = DB::table('users')->count();
 
$price = DB::table('orders')->max('price');
 
$price = DB::table('orders')->min('price');
 
$price = DB::table('orders')->avg('price');
 
$total = DB::table('users')->sum('votes');
  

原生表达式
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();<br><br>
1
whereRaw(可以加原生语句):例如:
TrGoModel::query()->whereRaw('id = 286')->first();
添加
添加数据进数据表
DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);
添加自动递增 (Auto-Incrementing) ID 的数据至数据表
如果数据表有自动递增的ID,可以使用 insertGetId 添加数据并返回该 ID:
 
$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);
注意: 当使用 PostgreSQL 时,insertGetId 方法会预期自动增加的字段是以「id」为命名。
 
添加多个数据进数据表
DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);
更新
更新数据表中的数据
DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);
自增或自减一个字段的值
DB::table('users')->increment('votes');
 
DB::table('users')->increment('votes', 5);
 
DB::table('users')->decrement('votes');
 
DB::table('users')->decrement('votes', 5);
也能够同时指定其他要更新的字段:
 
DB::table('users')->increment('votes', 1, ['name' => 'John']);
 

删除
删除数据表中的数据
DB::table('users')->where('votes', '<', 100)->delete();
删除数据表中的所有数据
DB::table('users')->delete();
清空数据表
DB::table('users')->truncate();
Unions
查询构造器也提供一个快速的方法去「合并 (union)」两个查找的结果:
 
$first = DB::table('users')->whereNull('first_name');
 
$users = DB::table('users')->whereNull('last_name')->union($first)->get();
unionAll 方法也可以使用,它与 union 方法的使用方式一样。
  

悲观锁定 (Pessimistic Locking)
  
查询构造器提供了少数函数协助你在 SELECT 语句中做到「悲观锁定」。
 
想要在 SELECT 语句中加上「Shard lock」,只要在查找语句中使用 sharedLock 函数:
 
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
要在 select 语法中使用「锁住更新(lock for update)」时,你可以使用 lockForUpdate方法:
 
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
  

从数据表中分块查找数据列:
<?php
$users = DB::table('users')->chunk(100, function(){
     foreach($users as $user){
          return false; // 返回false停止处理接下来的数据列
     }
 
})
?> 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值