laravel框架总结 -- 返回值

来源:互联网 发布:淘宝开店要交押金吗? 编辑:程序博客网 时间:2024/06/05 16:09
以前用CI框架对于返回值没有过多关注,但是发现使用laravel框架的时候出现了一些小问题,特意实践总结了一些常用情形,希望对大家有所帮助
 
  先理解几个概念:
   1>StdClass 对象=>基础的对象
   2>Eloquent 模型对象(Model 对象)=>和模型相关的类对象
   3>Eloquent 集合=>可以简单理解为对象数组,里面的每一个元素都是一个Model 对象
   注明:对象和实例只是说法不同,就是实例化的类,称谓只是一个代号,大家理解实质即可
 
1.使用DB门面查询构造器
  1>$test = DB::table('dialog_information')->get();
  返回值: 方法会返回一个数组结果,其中每一个结果都是 PHP StdClass 实例
 
  2>$test = DB::table('dialog_information')->first();
  返回值:这个方法会返回单个 StdClass 实例
2.使用orm模型
  1>$list = Dialog::first();
  返回值:Eloquent 模型对象
 
  2>$list = Dialog::find(1);
  返回值:Eloquent 模型对象
 
  3>$list = Dialog::get();
  返回值:Eloquent 集合
 
  4>$list = Dialog::all();
  返回值:Eloquent 集合
 
  5>$input = ['goods_id'=>1,'buyer_id'=>1,'seller_id'=>1];
  $result = Dialog ::create($input);
  dd($result);
  返回值:Eloquent 模型对象
 
3.关于使用orm模型增删改的一些总结

//save 返回真假

  $dialog = new Dialog();

  $dialog->goods_id = 1;

  $dialog->buyer_id = 2;

  $dialog->seller_id = 3;

  $result = $dialog->save();

//create 返回Eloquent 模型对象

  $input = ['goods_id'=>1,'buyer_id'=>1,'seller_id'=>1];

  $result = Dialog ::create($input);

//insert 返回真假

  $data = array(array('goods_id'=>1,'buyer_id'=>1,'seller_id'=>1),array('goods_id'=>2,'buyer_id'=>2,'seller_id'=>2));

  $result = Dialog::insert($data);

//delete 返回真假

  $dialog = Dialog::find(10);

  $result = $dialog->delete();

//destroy 返回删除条数

  $result = Dialog::destroy([11,12]);

//delere和where使用 返回删除条数

  $result = Dialog::where('id', '>', 10)->delete();

//update 返回更新条数

  $result = Dialog::where('id', '>', 10)->update(['seller_id'=>3]);
4.分析Model实例
测试代码:
  $account = Users::find(1)->account;
  $account->newAttr = 'test';
  $account->table = 'testTable';
  var_dump($account->primaryKey);
  dd($account);
输出结果:
 
分析:
  1.首先进入Model文件,发现我们有一些public修饰的模型约定,然后进入模型继承的类,发现里面有protect修饰的字段,这些字段就是我们上面输出的内容
  2.如果我们想取到table对应的值,那么直接$account->primaryKey,就可以得到对应的值 id
  3.注意到,我们$account->qq可以取出对应的值111111,如果User_account下第一层没有取到,那么就回去attributes下面寻找,然后取出qq对应的值
  4.测试代码中
    $account->newAttr = 'test'; //在attributes中产生了一个新键值对
    $account->table = 'testTable'; //发现User_account下第一层中的table被修改了,而没有修改到attributes中.