Eloquent ORM数据库操作
数据库操作
数据库的配置文件放置在 config/database.php
文件中,你可以在此定义所有的数据库连接,并指定默认使用的连接。此文件内提供了大部分 Laravel 能支持的数据库配置示例。
CURD查询构造器
<?php
//laravel5.6 语法 demo示例
namespace App\Http\Controllers;//命名该控制App空间下名称
use Illuminate\Support\Facades\DB;//使用DB操作数据库
use App\Http\Controllers\Controller;//继承基础控制器
class UserController extends Controller
{
/**
* 展示应用的用户列表.
*
* @return Response
*/
public function index()
{
//DB使用为每种操作提供了相应方法:
select(查),update(修改),insert(插入),delete(删除),statement(声明)
//建议占位符,其他框架通用性强
//原生sql写法
$data = DB::select('select * from users where id = :id and name = :name ',[':id' => 1,':name' =>'测试']);
//查方法
//get() 方法获取表中所有记录(获取多行多列)
$data = DB::table('users')->get();
//first() 方法将会返回单个对象(获取一行一列)
//where() 方法查询指定条件对象
$data = DB::table('users')->where('id','name','3','测试')->first();
//select() 方法可以查询指定自定义字段
$data = DB::table('users')->select('id','name', 'email')->get();
//value() 方法从结果中获取单个值,该方法会直接返回指定列的值:
$data = DB::table('users')->where('name','测试')->value('email');
//pluck() 方法获取单个列值的数组
$data = DB::table('users')->pluck('name');
//count() 统计数量
$data = DB::table('users')->count();
//exists() 方法来判断匹配查询条件的结果是否存在
$data=DB::table('users')->where('id', 1)->exists();
//join() 方法连表查询
$data = DB::table('users')
->join('ceshi', 'users.id', '=', 'ceshi.id')
->select('users.*', 'ceshi.name')
->get();
//leftJoin() 方法左连表查询
$data = DB::table('users')
->leftJoin('ceshi', 'users.id', '=', 'ceshi.id')
->select('users.*', 'ceshi.name')
->get();
//where() 参数说明:(一)参数是列名,(二)参数是操作符,(三)参数是该列要比较的值
$data = DB::table('users')
->where('id', '>=', 1)
->where('name', 'like', '测试%')
->get();
//传递条件数组到where中写法,建议多where查询使用这个方法
$data = DB::table('users')
->where([
['id', '>=', 1],
['name', 'like', '测试%']
])
->get();
//whereBetween() 方法验证列值是否在给定值之间
$data = DB::table('users')
->whereBetween('id', [1, 3])->get();
//whereIn 方法验证给定列的值是否在给定数组中:
$data = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
//orderBy() 方法排序
$data = DB::table('users')
->orderBy('id', 'desc')
->get();
//insert() 方法插入记录到数据表
//insertGetId() 方法插入记录并返回自增ID值
$data=DB::table('users')->insert(
[
'name'=>'测试',
'email' => 'ceshi.com',
'password' => 'ceshi'
]
);
//update() 方法修改记录
$data =DB::table('users')
->where('id', 1)
->update(['name' => '测试']);
//delete() 方法删除记录
$data=DB::table('users')->where('id', '>', 10)->delete();
//paginate() 方法分页 每页显示数量
//注意:目前使用 groupBy 的分页操作不能被Laravel有效执行
$data = DB::table('users')->paginate(2);
//前台分页中链接附加参数实现分页
$getName = $GET['name']?:'';
$data = DB::table('users')
->select('id','name','age')
->where('name', 'like', $getName.'%')
->paginate(2);
//返回给前端视图数据
return $this->view('index',['data'=>$data,'namePage'=>$getName]);
//前端引用代码
//appends 方法添加查询参数到分页链接查询字符串; 添加 &name=$namePage到每个分页链接中.
{ { $data->appends( ['name' => $namePage] )->links() } }
//simplePaginate() 方法分页视图中简单的显示“下一页”和“上一页”链接
$data = DB::table('users')->simplePaginate(2);
//返回给前端视图数据
return $this->view('index',['data'=>$data]);
//前端简单引用代码
<div class="container">
@foreach ($users as $user)
{ { $user->name } }
@endforeach
</div>
{ { $data->links() } }
//原生分页写法
$page = 2;
$pageSize = 1;
$offset = ($page - 1) * $pageSize;
$result = DB::table('picasa')
->where('title', 'like', '%'.$title.'%')
->offset($offset)
->limit($pageSize)
->get();
//返回数据视图文件
return $this->view('index', ['result' => $result]);
}
}
开启sql查询日志
DB::connection()->enableQueryLog();//开启QueryLog
$data = DB::table('users')->select('id','name', 'email')->get();//执行sql
dump(DB::getQueryLog());//sql语句和查询时间
写入日志信息
八种日志级别:emergency、alert、critical、error、warning、 notice、info 和 debug
默认日志存放位置: /storage/logs/laravel.log
引用: use Illuminate\Support\Facades\Log
Log::emergency(string $message, array $context = []);
Log::alert(string $message, array $context = []);
Log::critical(string $message, array $context = []);
Log::error(string $message, array $context = []);
Log::warning(string $message, array $context = []);
Log::notice(string $message, array $context = []);
Log::info(string $message, array $context = []);
Log::debug(string $message, array $context = []);
Eloquent ORM操作数据
自动建立Users模型
php artisan make:model Users
手动建立Users模型
<?php
namespace App\Model\Eloquent\Admin;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
//指定表名
protected $table="users";
//指定id
protected $primaryKey="id";
//指定允许批量的字段
protected $fillable=['name','age'];
//指定不允许批量赋值的字段
protected $guarded=[];
//连接多数据库配置 默认使用'mysql'
protected $connection = 'mysql';
//自动维护时间戳 默认是'true'
public $timestamps=true;
//返回当前时间的时间戳,进入数据库,输出时,可以输出格式化好的时间
protected function getDateFormat()
{
return time();
}
//设置之后,返回的就是数据表中的时间戳
protected function asDateTime($value)
{
return $value;
}
}
引用Users模型
use App\Model\Eloquent\Admin\Users;
ORM 查
//all() 查询所有数据 查询数据为集合
$data=Users::all();
//根据[$id]主键查询 查询一条数据
$data=Users::find($id);
//findOrFail() 根据主键查询 如果没有查到 报错
$data=Users::findOrFail($id);
//get() 查询所有数据
$data=Users::get();
//first() 查询第一条
$data=Users::where('id','>','1')->orderBy('age','desc')->first();
//chunk() 每次查询指定[$num]条数
Users::chunk($num,function($data){
print_r($data);
} );
//聚合函数
//count() 统计记录条数
$num = Users::count();
//max() 查询最大值 min() 查询最小值
$max=Users::where('id','>',1)->max('age');
ORM 增
//save() 单增
$data = new Users();
$data->name = 'admin_a';
$data->age = 100;
$data->save();
//create() 多增
$ret=Users::create( [
'name'=>'admin_b',
'age'=>200
] );
//firstOrCreate()以属性查询数据 如果没有 新建数据
$ret=Users::firstOrCreate( [
'name'=>'admin_c',
'age'=>300
] );
//firstOrNew() 以属性查询数据 如果没有 新建实例 如果想保存调用save()
$ret=Users::firstOrNew( [
'name'=>'admin_d',
'age'=>400
] );
$ret->save();
ORM 改
//获取主键id,模型修改数据
$data=Users::find($id);
$data->name ='admin_e';
$data->age =66;
$data->save();
//批量修改
$ret=Users::where('id','>',2)->update(
['age'=>33]
);
ORM 删
//获取主键id,模型删除单条
$data=Users::find($id);
$data->delete();
//通过主键删除多条
$ret=Users::destroy(1,2,3);
$ret=Users::destroy([4,5,6]);
//删除指定条件
$ret=Users::where('id','>',2)->delete();