search
HomePHP FrameworkLaravelDetailed explanation of Laravel ORM operations

The following tutorial column will introduce you to the detailed explanation of Laravel ORM operations. I hope it will be helpful to friends who need it!

##1. Laravel gets the last sql statement and the passed-in value:

    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 "
";Go directly Picture:

Take out some data:

    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;     }

Detailed explanation of Laravel ORM operations

##Create if it does not exist, update if it exists:

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

Laravel subquery, multi-condition judgment:

    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);
    }
Detailed explanation of Laravel ORM operationsLaravel runs complex native statements:

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

sql clauses can be written directly in selectRaw


The above is the detailed content of Detailed explanation of Laravel ORM operations. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Full-Stack Development with Laravel: Managing APIs and Frontend LogicFull-Stack Development with Laravel: Managing APIs and Frontend LogicApr 28, 2025 am 12:22 AM

In Laravel full-stack development, effective methods for managing APIs and front-end logic include: 1) using RESTful controllers and resource routing management APIs; 2) processing front-end logic through Blade templates and Vue.js or React; 3) optimizing performance through API versioning and paging; 4) maintaining the separation of back-end and front-end logic to ensure maintainability and scalability.

Lost in Translation: Cultural Nuances and Misunderstandings in Distributed TeamsLost in Translation: Cultural Nuances and Misunderstandings in Distributed TeamsApr 28, 2025 am 12:22 AM

Totackleculturalintricaciesindistributedteams,fosteranenvironmentcelebratingdifferences,bemindfulofcommunication,andusetoolsforclarity.1)Implementculturalexchangesessionstosharestoriesandtraditions.2)Adjustcommunicationmethodstosuitculturalpreference

Measuring Connection: Analytics and Insights for Remote Communication EffectivenessMeasuring Connection: Analytics and Insights for Remote Communication EffectivenessApr 28, 2025 am 12:16 AM

Toassesstheeffectivenessofremotecommunication,focuson:1)Engagementmetricslikemessagefrequencyandresponsetime,2)Sentimentanalysistogaugeemotionaltone,3)Meetingeffectivenessthroughattendanceandactionitems,and4)Networkanalysistounderstandcommunicationpa

Security Risks in Distributed Teams: Protecting Data in a Remote WorldSecurity Risks in Distributed Teams: Protecting Data in a Remote WorldApr 28, 2025 am 12:11 AM

Toprotectsensitivedataindistributedteams,implementamulti-facetedapproach:1)Useend-to-endencryptionforsecurecommunication,2)Applyrole-basedaccesscontrol(RBAC)tomanagepermissions,3)Encryptdataatrestwithkeymanagementtools,and4)Fosterasecurity-consciousc

Beyond Email: Exploring Modern Communication Platforms for Remote CollaborationBeyond Email: Exploring Modern Communication Platforms for Remote CollaborationApr 28, 2025 am 12:03 AM

No, emailisnotthebostforremotecollaborationToday.Modern platformlack, Microsoft teams, Zoom, ASANA, AndTrelloFhertreal-Time Communication, Project management, Andintegrationfeaturesthancteamworkandefficiency.

Collaborative Document Editing: Streamlining Workflow in Distributed TeamsCollaborative Document Editing: Streamlining Workflow in Distributed TeamsApr 27, 2025 am 12:21 AM

Collaborative document editing is an effective tool for distributed teams to optimize their workflows. It improves communication and project progress through real-time collaboration and feedback loops, and common tools include Google Docs, Microsoft Teams, and Notion. Pay attention to challenges such as version control and learning curve when using it.

How long will the previous Laravel version be supported?How long will the previous Laravel version be supported?Apr 27, 2025 am 12:17 AM

ThepreviousversionofLaravelissupportedwithbugfixesforsixmonthsandsecurityfixesforoneyearafteranewmajorversion'srelease.Understandingthissupporttimelineiscrucialforplanningupgrades,ensuringprojectstability,andleveragingnewfeaturesandsecurityenhancemen

Leveraging Laravel's Features for Both Frontend and Backend DevelopmentLeveraging Laravel's Features for Both Frontend and Backend DevelopmentApr 27, 2025 am 12:16 AM

Laravelcanbeeffectivelyusedforbothfrontendandbackenddevelopment.1)Backend:UtilizeLaravel'sEloquentORMforsimplifieddatabaseinteractions.2)Frontend:LeverageBladetemplatesforcleanHTMLandintegrateVue.jsfordynamicSPAs,ensuringseamlessfrontend-backendinteg

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!