大飞_dafei

导航

laravel controller 层---数据库操作

001) 特别篇

$user = Student::pluck('name');    // 
Student::query()->pluck('name');  // idea 有提示

002) 使用union 后 使用 fromSub(aaa,bbb) 可以使用union后的结构

1) 查询

集合--处理数组

数据库操作 - 查询构建器

$users = DB::table('student_01')->get();


//尽量不使用这种方式查询数据,使用上面一种方式查询
$result = DB::select(DB::raw('SELECT * FROM student WHERE name=:name '),
[
'name'=>'张三'
]);

dd($result);


$arr = [1, 2, 3, 4];
 // $brr = "1,2,3,4";  //这种方法,SQL对,但是结果会只去一条数据
$bbb = Student::select('*')->whereIn('id',$arr)->get()->toArray();


//使用模型关联 hasOne hasMany with
$topics = Topic::limit(2)->with(['user'=>function($query){
   $query->select('id','username');
}])->get();
public function user(){ //model层
  return $this->hasOne("Student::class",'u_id','id')
}

$topics = Topic::limit(2)->with(['user'=>function($query)use ($login){//$login 传值
    $query->where('id',$login['id'])->select('id','username');
}])->get();


//pluck 获取所有集合值:
$user = Student::pluck('name');
Student::pluck('name')->implode(',')  //取出后拼接字符串
相关参考地址 https://laravelacademy.org/post/9566.html
$allSum = Student::query()
    ->whereBetween('consumeTime', ['2021-02-18 00:00:00', '2021-02-28 11:59:59'])
    // ->where("consumeTime",'>=','2021-02-18 00:00:00')
    // ->where("consumeTime",'<=','2021-02-28 11:59:59')
    ->sum('countPrice'); // 区间求和

 

2) 获取 SQl

DB::table('student')->toSql();

2-02)  
DB::enableQueryLog();             
$aa = DB::getQueryLog();
打印 $aa

 

3) 修改

//修改
$user = UserModel::find($id);
$user->title = $_POST['title'];
$user->content= $_POST['content'];
return $user->save() ? 'OK' : 'fail';

//修改2
Student01::where('m_id', '=', '12')
->update([
    'field1'=>'ttt',
    'field2'=>'uuuuuuuu'
]);

//修改3
$model = GenericName::find($id);
$model->fill($input)->save();

4) hasOne hasMany 使用with,并在with中使用条件

laravel中使用with如何动态添加where条件

posted on 2020-10-14 09:14  大飞_dafei  阅读(273)  评论(0编辑  收藏  举报