首页  >  文章  >  php框架  >  关于Laravel ORM操作的详解

关于Laravel ORM操作的详解

藏色散人
藏色散人转载
2021-04-20 09:42:243298浏览

下面由laravel教程栏目给大家介绍详解Laravel ORM操作,希望对需要的朋友有所帮助!

1、laravel获取最后一条sql语句和传入的值:

    public function getOrderDetail($orderId){

        \DB::connection()->enableQueryLog(); // 开启查询日志  

        $ordeList = OrderItem::where('order_id',$orderId)
            ->get()->toArray();        $queries = \DB::getQueryLog(); // 获取查询日志  

        echo "<pre class="brush:php;toolbar:false">";
            print_r($queries);            echo PHP_EOL;
            print_r($ordeList);        echo "
";

直接上图:

这里写图片描述

取出部分数据:

    public function getOrderDetail($uid,$orderId){
        $user = $this->check_user($uid);        $columns = [&#39;id&#39;, &#39;order_id&#39;, &#39;item_id&#39;, &#39;item_name&#39;, &#39;item_price&#39;, &#39;original_price&#39;, &#39;buy_num&#39;, &#39;real_num&#39;, &#39;cancel_num&#39;, &#39;status&#39;, &#39;create_time&#39;];        $ordeList = OrderItem::where(&#39;order_id&#39;,$orderId)
            -> orderBy(&#39;create_time&#39;,&#39;desc&#39;)
            ->get($columns)->toArray();        echo "<pre class="brush:php;toolbar:false">";
            print_r($ordeList);        echo "
"; exit; }

这里写图片描述

不存在就创建,存在就更新:

Model::updateOrCreate(
   [&#39;primary_key&#39; => 8],
   [&#39;field&#39; => &#39;value&#39;, &#39;another_field&#39; => &#39;another value&#39;]
);

Laravel子查询,多条件判断:

    public function getCourseProgress($uid,$levelId=0,$lessonId=0,$type=0,$page=0)
    {
        //检测用户合法性
        $user = $this->check_user($uid);        //当前页数
        $page = $page>0?$page:0;        //每页显示数量
        $perPage = config(&#39;bcc.per_page&#39;);        //显示字段
        $columns = [&#39;*&#39;];        #课程学习进度信息
        $result = LessonProgress::where(&#39;customer_id&#39;,$uid)
            ->where(function($query) use ($type){
                if($type) $query->where(&#39;source_type&#39;,$type);
            })
            ->where(function($query) use ($levelId,$lessonId){
                if($levelId && $lessonId) {                    $query->where([&#39;level_id&#39;=>$levelId,&#39;lesson_id&#39;=>$lessonId]);
                }elseif($levelId){                    $query->where(&#39;level_id&#39;, $levelId);
                }
            })->get();            //->paginate($perPage,$columns,$pageName=&#39;&#39;,$page);

        if($result->isEmpty()) return $this->responseSuccess([],&#39;No relevant information&#39;,20000);        return $this->responseCollection($result,new CourseProgressTransformer);
    }

Laravel运行复杂的原生语句:

    // 声母韵母分两类
    $data=Pronounce::selectRaw(&#39;group_concat(`letter`) as letters&#39;)
    ->groupBy(&#39;pronounce_type&#39;)
    ->get()
    ->toArray();

selectRaw里面可以直接写sql子句

以上是关于Laravel ORM操作的详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:csdn.net。如有侵权,请联系admin@php.cn删除