Laravel实用知识记录
一、定义全局公用方法
习惯了tp的肯定希望在laravel中也可以定义全局的公共方法。
以我的个人习惯为例,在app下新建Common文件夹,并在Common文件夹中新建function.php文件。
然后在composer.json文件中找到aucoload配置项,在其中添加添加
"files": [
"app/Common/function.php"
]
然后在命令行使用composer dump-autoload更新自动加载文件,执行成功后即可在全局使用在function.php文件中定义的方法。
二、接受json数据
1、在上面定义的function.php文件中封装接收方法
function json_params()
{
$data = json_decode(file_get_contents('php://input'), true);
return $data;
}
2、利用laravel中的Request类;
use Illuminate\Http\Request;
public function index(Request $request)
{
//第一种方法
$params = $request->json()->all(); //这里返回的结果是一个数组
return $params['id'];
//第二种方法,使用Request的input方法获取请求中的整个JSON或者具体key的值
//发送 JSON 请求到Laravel应用的时候,只要 Content-Type 请求头被设置为application/json,都可以通过input方法获取 JSON 数据
//还可以通过“.”号解析数组
$foo=$request->input('foo'); //echo$foo=>'bar'
//使用点号获取内嵌数组key的值
//假设请求体中的JSON为 {"user": {"name":"kevin","age": 18}}
$name=$reqeust->input('user.name');//echo$name=>'kevin'
}
三、事务
$data['addtime'] = time();
DB::beginTransaction();
try {
$this::create($data);
DB::table('test1')->where('id', $data['obj_id'])->increment('comment_num');
DB::table('test2')->where('id', $data['obj_id'])->increment('comment_num');
DB::commit();
} catch (QueryException $exception) {
DB::rollback();
}
四、ORM
1、where多条件查询加手动分页
$data = $this::where('comment_id', $comment_id)
->where('is_delete', 0)
->where('reply_state', 0)
->orderBy('addtime')
->offset($page * $page_size)
->limit($page_size)
->get();
2、模型类中ORM插入数据
$data['value'] = 1;
$data['addtime'] = $time;
$res = $this::create($data);
3、模型类中ORM更新数据
$save_data['is_read'] = 0;
$save_data['modify_time'] = $time;
$res = $this::where('id', 1)->update($save_data);
4、查单条数据
$obj_data = DB::table('test')->find($id);
或者
$obj_data = DB::table('test')->where('id', $id)->first();