Laravel ORM 数据model操作

童冠玉
2023-12-01
 
随机查询
$data=Move::where('release',1)
    ->where('is_hot',1)
    ->where('is_status',1)
    ->orderBy(\DB::raw('RAND()'))
    ->take(4)
    ->get();

 

1.ORM操作需要创建对应的model
        
class User extends Eloquent

 

2.两种方式使用数据操作对象
           a. 使用new关键字创建对象后执行对象的方法
           b. 直接调用static方法(实际并发静态方法,而是fascade生成的)
 
3.常用数据操作
User::find(1)      查找单条数据
User::all()        查找所有数据
User::first()      取第一条数据
User::pluck('artist');  返回表中该字段的第一条记录
User::lists('artist');  返回一列数据
User::save()            保存数据
User::truncate()        清空数据表,危险操作
User::find(1)->delete()        删除单条数据
User::destory(array(1,2,3))    删除单条或多条数据

指定查询条件,更新数据
Album::where('artist', '=', 'Matt Nathanson') ->update(array('artist' => 'Dayle Rees')); 
   
配合查询条件获取多条数据
Album::where('artist', '=', 'Something Corporate')->get(array('id','title'));   

获取查询的sql语句,仅用于条件,不能用户带get()之类的带查询结果的查询中
Album::where('artist', '=', 'Something Corporate')->toSql();     

 

条件查询:
   1. 最普通的条件查询
               User::where('字段名','查询字符','限制条件')     例:Album::where('title', 'LIKE', '...%')
   2. 多条件查询,使用多个where  
               User::where('title', 'LIKE', '...%')->where('artist', '=', 'Say Anything')->get();
   3. 或查询操作使用
               orWhere(),使用方法通where
   4.直接用sql语句写查询条件
               Album::whereRaw('artist = ? and title LIKE ?', array('Say Anything', '...%'))
   5. 其他查询方法
               whereIn(),whereBetween(),whereNested()子查询,orWhereNested(),whereNotIn(),whereNull(),whereNotNull()
   6. 快捷方式  
               whereUsername('king')  查询'username' = 'king'的数据,默认系统无此方法,username为字段名称
 
结果排序: order()
Album ::where( 'artist''=''Matt Nathanson') ->orderBy( 'year') ->get();   默认asc, desc:orderBy( 'year''desc')
 
限制结果数量: take()
Album::take(2)->get();  //select * from `albums` limit 2
 
指定偏移
    Album::take(2)->skip(2)->get();  //select * from `albums` limit 2 offset 2
 类似资料: