首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii2 ActiveRecord 多表關聯與關聯搜索實現:GridView 顯示關聯字段、優化 SQL、SearchModel 過濾

     編輯:PHP 綜合知識

場景需求

用戶表 user 與認證表 auth 通過 user.id = auth.uid 一對一關聯。需在 User 列表(GridView)顯示 auth.source 並支持搜索過濾。

步驟 1:模型定義關聯

// common/models/User.php
public function getAuth() {
    return $this->hasOne(Auth::className(), ['uid' => 'id']);
}

步驟 2:GridView 直接使用關聯屬性(觸發 N+1)

'columns' => [
    // ...
    'auth.source', // 直接用關聯路徑
]

Debug 面板顯示:分頁 20 條 → 20 條 SELECT * FROM auth WHERE uid=... SQL,性能差。

步驟 3:SearchModel 優化 - joinWith + select

// common/models/UserSearch.php
public function search($params) {
    $query = User::find();
    // 關鍵:joinWith 產生 LEFT JOIN,select 只取需要字段
    $query->joinWith(['auth']);
    $query->select("user.*, auth.source");

    $dataProvider = new ActiveDataProvider(['query' => $query]);
    // ... load($params) validate() ...
    return $dataProvider;
}

SQL 變為:

SELECT `user`.*, `auth`.`source` FROM `user` LEFT JOIN `auth` ON `user`.`id` = `auth`.`uid` LIMIT 20

只剩 1 條 SQL,性能大幅提升。

步驟 4:關聯字段加入搜索過濾

4.1 SearchModel 定義屬性與規則

public $source; // 虛擬屬性接收搜索值

public function rules() {
    return [
        // ...
        ['source', 'safe'], // 允許搜索
    ];
}

4.2 GridView 列配置

[
    'attribute' => 'source',
    'value' => 'auth.source',
    'label' => '渠道來源',
]

4.3 查詢條件加入過濾

$query->andFilterWhere([
    // ...
    'auth.source' => $this->source,
]);

補充:ActiveRecord 常用技巧

需求代碼
對象轉數組 (可 json_encode)$model->toArray()
按條件查單條並取字段User::find()->where(['like','name', $str])->select('id')->scalar()
動態調用 model()call_user_func([ActiveRecord::className(), 'model'])

總結

  1. 模型定義 hasOne/hasMany 關聯
  2. GridView 直接用 relation.field 顯示(開發期可接受)
  3. 生產環境 SearchModel 中 joinWith + select 優化為單 SQL
  4. 搜索需:虛擬屬性 + rules safe + GridView attribute/value + andFilterWhere
  5. 善用 toArray() 序列化、scalar() 取單值

這套模式可直接套用於任何一對一/一對多關聯的列表顯示與搜索場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved