


The difference between has and with in Laravel association model (detailed introduction)
The content of this article is about the difference between has and with in Laravel association model (detailed introduction). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First look at the code:
$userCoupons = UserCoupons::with(['coupon' => function($query) use($groupId){ return $query->select('id', 'group_id', 'cover', 'group_number', 'group_cover')->where([ 'group_id' => $groupId, ]); }]) // 更多查询省略...
The data structure is three tables: user coupon table (user_coupons), coupon table (coupons), merchant table (corps), and group coupons Table (group_coupons) (for the convenience of viewing, the last two items have been removed)
Here I originally intended to use model association to find out all the data belonging to the given group gourpId in the user coupons (if it is empty, the data will be not returned).
But some results are not what I want:
array(20) { ["id"]=> int(6) ["user_id"]=> int(1) ["corp_id"]=> int(1) ["coupon_id"]=> int(4) ["obtain_time"]=> int(1539739569) ["receive_time"]=> int(1539739569) ["status"]=> int(1) ["expires_time"]=> int(1540603569) ["is_selling"]=> int(0) ["from_id"]=> int(0) ["sell_type"]=> int(0) ["sell_time"]=> int(0) ["sell_user_id"]=> int(0) ["is_compose"]=> int(0) ["group_cover"]=> string(0) "" ["is_delete"]=> int(0) ["score"]=> int(100) ["created_at"]=> NULL ["updated_at"]=> NULL ["coupon"]=> NULL // 注意返回了coupons为空的数据 }
Some coupons in the records have records, and some are empty. Think about it, with is just the so-called preloading implemented using sql's in(). No matter what the main user_coupons data will be listed.
It will have two sql queries, the first one checks the main data, the second one checks the association. The second sql here is as follows:
select `id`, `group_id`, `cover`, `group_number`, `group_cover` from `youquan_coupons` where `youquan_coupons`.`id` in (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14) and (`group_id` = 1) and `youquan_coupons`.`deleted_at` is null
If the second one is empty, the main record The associated field is NULL.
Later I saw the has() method of Laravel's associated model. has() is based on the existing associated query. Below we use whereHas() (the same effect, just more advanced, convenient for writing conditions)
Our idea here is to put the judgment of whether there is coupon data in the first query logic, so that we can filter out empty records.
The code after adding whereHas() is as follows
$userCoupons = UserCoupons::whereHas('coupon', function($query) use($groupId){ return $query->select('id', 'group_id', 'cover', 'group_number', 'group_cover')->where([ 'group_id' => $groupId, ]); })->with(['coupon' => function($query) use($groupId){ return $query->select('id', 'group_id', 'cover', 'group_number', 'group_cover'); }])-> // ...
Look at the final SQL:
select * from `youquan_user_coupons` where exists (select `id`, `group_id`, `cover`, `group_number`, `group_cover` from `youquan_coupons` where `youquan_user_coupons`.`coupon_id` = `youquan_coupons`.`id` and (`group_ids` = 1) and `youquan_coupons`.`deleted_at` is null) and (`status` = 1 and `user_id` = 1)
Here actually uses exists() to filter existing records. Then go to the next step of the with() query. Because everything has been filtered at this time, with can remove the condition.
Obviously it is important to distinguish between the two functions, especially in lists. There is no need to specifically filter out empty data, and it is easy to do paging.
The above is the detailed content of The difference between has and with in Laravel association model (detailed introduction). For more information, please follow other related articles on the PHP Chinese website!

LaravelBladeenhancesfrontendtemplatinginfull-stackprojectsbyofferingcleansyntaxandpowerfulfeatures.1)Itallowsforeasyvariabledisplayandcontrolstructures.2)Bladesupportscreatingandreusingcomponents,aidinginmanagingcomplexUIs.3)Itefficientlyhandleslayou

Laravelisidealforfull-stackapplicationsduetoitselegantsyntax,comprehensiveecosystem,andpowerfulfeatures.1)UseEloquentORMforintuitivebackenddatamanipulation,butavoidN 1queryissues.2)EmployBladetemplatingforcleanfrontendviews,beingcautiousofoverusing@i

Forremotework,IuseZoomforvideocalls,Slackformessaging,Trelloforprojectmanagement,andGitHubforcodecollaboration.1)Zoomisreliableforlargemeetingsbuthastimelimitsonthefreeversion.2)Slackintegrateswellwithothertoolsbutcanleadtonotificationoverload.3)Trel

Remoteaccessandscreensharingworkbyestablishingasecure,real-timeconnectionbetweencomputersusingprotocolslikeRDP,VNC,orproprietarysolutions.Bestpracticesinclude:1)Buildingtrustthroughclearcommunication,2)Ensuringsecuritywithstrongencryptionandup-to-dat

Definitely worth considering upgrading to the latest Laravel version. 1) New features and improvements, such as anonymous migration, improve development efficiency and code quality. 2) Security improvement, and known vulnerabilities have been fixed. 3) Community support has been enhanced, providing more resources. 4) Compatibility needs to be evaluated to ensure smooth upgrades.

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

Laravel remains the preferred framework for PHP developers as it excels in development experience, community support and ecosystem. 1) Its elegant syntax and rich feature set, such as EloquentORM and Blade template engines, improve development efficiency and code readability. 2) The huge community provides rich resources and support. 3) Although the learning curve is steep and may lead to increased project complexity, Laravel can significantly improve application performance through reasonable configuration and optimization.

Building a live chat application in Laravel requires using WebSocket and Pusher. The specific steps include: 1) Configure Pusher information in the .env file; 2) Set the broadcasting driver in the broadcasting.php file to Pusher; 3) Subscribe to the Pusher channel and listen to events using LaravelEcho; 4) Send messages through Pusher API; 5) Implement private channel and user authentication; 6) Perform performance optimization and debugging.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
