yii2 ActiveRecord多表关联以及多表关联搜索的实现,yii2activerecord_PHP教程
yii2 ActiveRecord多表关联以及多表关联搜索的实现,yii2activerecord
一个老生常谈的问题。最近通过群里的反馈,觉得很多人还是没有去理解这个问题。今天把这个问题讲明白了,看看yii2 ActiveRecord是怎么个多表关联以及如何去优化这个关联。
场景需求:
假设我们有一张用户表user和一张用户渠道表auth,两张数据表通过user.id和auth.uid进行一对一关联。现需要在user列表展示auth表的来源渠道source,且该渠道可搜索。
首先我们先通过gii生成user和auth系列相关的model和操作。此处不做详细说明,有关gii的操作可参考xxx
我看继续看重要的几个操作步骤:
1、找到user表对应的AR模型类 common\models\User.php,在该类文件中进行关联auth表
<span>/*</span><span>* * 关联auth表<br /> * @see http://www.manks.top/yii2_many_ar_relation_search.html </span><span>*/</span> <span>public</span> <span>function</span><span> getAuth() { </span><span>//</span><span> hasOne要求返回两个参数 第一个参数是关联表的类名 第二个参数是两张表的关联关系 // 这里uid是auth表关联id, 关联user表的uid id是当前模型的主键id</span> <span>return</span> <span>$this</span>->hasOne(common\models\Auth::className(), ['uid' => 'id'<span>]); }</span>
设置好了之后,并不代表两张数据表自动进行关联了!我们访问user列表页(该列表页采用gii生成,目前我们没操作过),通过debug查看Database Queries不难发现,实际中的query并没有进行关联auth表
2、在gridview中添加关联表的来源渠道字段source
<?= GridView::<span>widget([ </span><span>//</span><span> other codes</span> 'columns' =><span> [ </span><span>//</span><span> other columns</span> 'auth.source',<span> ] ]); </span>?>
有同学感觉疑问了,上面不是说了没进行关联吗,这个怎么可以直接使用auth.source?
先别急,此时我们打开debug看看实际的query。
我们会发现有很多类似 select * from `auth` where uid = xxx;之类的操作,如果你的分页默认20条数据时,会有20个类似的query。
我们先搞明白发生了什么?
实际上这属于php的基础知识了。读取和写入对象的一个不存在的成员变量时, __get() __set() 魔术函数会被自动调用。yii也是利用了这一点对其进行了实现!
该操作跟大部分人在gridview中封装方法获取关联表数据几乎一致,但是!20条sql的查询明显增加了众多的开销。如果这里是left join操作多好!
3、优化sql
我们需要优化的是:
20条sql变1条sql
只获取关联表需要的字段
有同学要嚷嚷了,这里是yii自带的操作,怎么优化?我们回到数据源的获取上,发现user列表的数据是通过userSearch model的search方法提供的。
也就是说我们的数据查询实际上就没有去进行关联表查询!既然如此,我们就在UserSearch加上关联查询
<span>$query</span> = User::<span>find(); </span><span>$query</span>->joinWith(['auth'<span>]); </span><span>$query</span>->select("user.*, auth.source");
我们再来刷新下user列表页,然后通过debug分析发现有两条sql引起了我们的注意
SELECT `user`.*, `auth`.`source` FROM `user` LEFT <span>JOIN</span> `auth` ON `user`.`id` = `auth`.`uid` LIMIT 20<span> SELECT </span>* FROM `auth` WHERE `user_id` IN (20个uid);
也就是说我么已经达到了优化sql的目的,通过debug分析发现,DB的查询时间少了很多。
4、关联表字段增加查询
gridview中的搜索模型也是通过searchModel实现的,该模型通过rules控制着哪个字段可搜索,哪个字段不可搜索。
我们现在需要增加关联表的source可搜索,因此我们在searchModel中定义一个属性source且添加到rules中
<span>public</span> <span>$source</span><span>; </span><span>public</span> <span>function</span><span> rules() { </span><span>return</span><span> [ </span><span>//</span><span> other rules</span> ['source', 'safe'],<span> ]; }</span>
接着我们把gridview中的auth.source修改一下
<span>//</span><span> 'auth.source',</span> <span>[ </span>'attribute' => 'source', 'value' => 'auth.source', 'label' => '渠道来源',<span> ]</span>,
到这里我们界面上是ok的,要实现程序上的搜索还差一步,我们在数据源获取的地方加上新增的source条件即可
<span>$query</span>-><span>andFilterWhere([ </span><span>//</span><span> other params</span> 'auth.source' => <span>$this</span>->source,<span> ]);</span>

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version
Useful JavaScript development tools
