webman在使用laravel的Eloquent-orm的一些经验
webman在使用laravel的Eloquent-orm的一些经验
之前一直用的think-orm,最近开始在webman中使用laravel的Eloquent-orm了,他们之间还是有一些差异的,这里记录一下
1、差异点
1、获取一条数据
// think-orm
$user = User::where($where)->find();
$user = User::find(1); //id=1的用户
//Eloquent ORM
$user = User::where($where)->first();
$user = User::find(1); //id=1的用户
2、获取多条数据
// think-orm
$user = User::where($where)->select();
//Eloquent ORM
$user = User::where($where)->get();
3、获取特定的字段
// think-orm
$user = User::where($where)->field('id,cinema_name')->select();
//Eloquent ORM
$user = User::where($where)->select(['id','cinema_name'])->get();
2、Eloquent-ORM的一些特别的点
1、查询条件
Eloquent-orm的查询运算符,不支持in,not in,between,not between,null,not null,这些都有专门的方法,例如 whereIn() ,whereNotIn
2、模型关联
Eloquent-orm的模型关联和think-orm基本一样,但是在获取关联模型数据的时候,比较简单。
$order = Orders::with([
'ordersDetail:id,order_id,item_total_fee,status,product_title'
])->where('user_id', 1)->where('order_sn', $params['order_sn'])->select(Orders::SHOW_FIELDS)->first();
3、获取特别的格式
//获取一些数据,id作为key,另一个字段作为value
$category = KfcCategory::pluck('name', 'id')->toArray();//结果 ["1" => "单人餐", "2" => "双人餐"]
//另一种
$category = KfcCategory::select(['id', 'name'])->get()->keyBy('id')->toArray();
//结果 ["1" => ["id" => 1,"name" => "单人餐"],"2" =>["id"=> 2,"name"=> "双人餐"]]
//只取单个字段的数据,并形成一维数组
$collect = UserStore::where('user_id', JwtToken::getCurrentId())->pluck('store_code')->toArray();
//结果 ["a123", "a234", "b123"]
//get出来总结果后,也可以再pluck
$crazy = self::with('product')->where('belong_date', date('Y-m-d'))->get();
$productNos = $crazy->pluck('product_no')->toArray();
本文链接:
/archives/1751505447438
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
雕刻时光!
喜欢就支持一下吧