Yii2 in indexBy () using

 

 

In project development often use to some special value as the array index, you can first check out the general format of the data array spliced ​​into the desired cycle. But YII2 framework provides an easier way indexBy ().

Yii Reference Document: https://www.yiichina.com/doc/guide/2.0/db-query-builder

When you call all () method, which returns a continuous integer value for the index of the array.
And sometimes you may want to use a specific value of the field or expression to the result set as an array index. Then you can call all () before using indexBy () method to achieve this objective.
E.g,

// to the key value as uid 
$ Query = the User :: Find ()
     -> SELECT ([ 'uid', 'name' ])
     -> indexBy ( 'uid' )
     -> asArray ()
     -> All ();

Query results are as follows:

{
  "1001": {
    "uid": "1001",
    "name": "张三"
  },
  "1002": {
    "uid": "1002",
    "name": "李四"
  },
  "1003": {
    "uid": "1003",
    "name": "王五"
  }
}

To use the value of the expression as an index, then only you need to pass the method an anonymous function to indexBy () to:

// to uid compositions as the key name and value 
$ Query = the User :: Find ()
     -> SELECT ([ 'uid', 'name' ])
     -> indexBy ( function ( $ Row ) {
         return  $ Row [ 'uid' .] $ row [ 'name'];    // field name can only be used in row returned by the query field name 
    })
     -> asArray ()
     -> All ();

Query results are as follows:

{
  "1001张三": {
    "uid": "1001",
    "name": "张三"
  },
  "1002李四": {
    "uid": "1002",
    "name": "李四"
  },
  "1003王五": {
    "uid": "1003",
    "name": "王五"
  }
}

Unlike groupBy () or orderBy () query method, etc., they will be converted into part of the SQL query, but this method (indexBy) come into force only after the retrieval of data from the database: Note. This means that only those using the column name in your SELECT query. In addition, when you connect with the name of the table to take the column name, such as customer.id, the results will contain only the id column, so you have to call -> indexBy ( 'id') not to take the table name prefix.

 

 

 

Guess you like

Origin www.cnblogs.com/woods1815/p/11917694.html