以前用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中.
以上都是親測,總結不全,歡迎補充