search
HomeBackend DevelopmentPHP TutorialDetailed examples of how to operate multi-table associations in YII2

Recently, I encountered problems related to YII2 multi-table association at work. I found that there is not much information on this aspect on the Internet, so I thought about sorting it out myself so that I can refer to it when I need it in the future or friends who need it can refer to it. The following article mainly introduces you to the use of multi-table associations in YII2. Friends who need it can take a look below.

Preface

This article gives a brief introduction to the multi-table related query of YII2.0. The article introduces it in detail through the example code. I won’t say much below. Let’s take a look at the detailed introduction:

First, let’s explain the table structure

Table structure

Now there are order table, user table, product list table, product inventory table

##In YII, if you want to directly associate other tables for query, you need to define their association in the model first

Order


class Order extends \yii\db\ActiveRecord.{
 
 // 关联函数以get+要关联的数据表名来命名
 // 这是获取下订单的客户
 public function getUser(){
  
  // 第一个参数为要关联的子表模型类名,
  // 第二个参数指定 通过子表的user_id,关联主表的usesr_id字段
  // 这里写清楚点大概意思就是User.user_id => Order.user_id
 return $this->hasMany(User::className(), ['user_id' => 'user_id']);
 }
}

1, hasMany, hasOne use

There are two types of associations between tables in Yii2, they use to specify the association between two models.

●One-to-many: hasMany ●One-to-one: hasOne


●Return results: The return results of these two methods are both yiidbActiveQuery objects (if you want to finally return Standard array form, remember to add asArray() parameter)


●The first parameter: the class name of the associated model.


●The second parameter: is an array, where the keys are the attributes in the associated model and the values ​​are the attributes in the current model.


Associated use

Now let’s try to get an order


//获取订单信息
$order = Order::findOne(1);
//根据订单信息获取到用户信息
$user = $order->user;

Of course you can choose to use the with method, which looks simpler. The parameter of with is the name of the relationship, which is the user.

in getUser defined in the model.

//返回订单信息(包括用户信息)
$order = Order::find(1)->with('user');
//或者
$order = Order::find(1)->getUser();

The above code will generate and execute the following sql statement


SELECT * FROM order WHERE id=1;
SELECT * FROM user  WHERE user.user_id=order.user_id;

It can be seen from the above that there are two ways to access an association. Method

●If called as a function, an ActiveQuery object will be returned ($customer->getOrders()->all())

●If called as an attribute Method call will directly return the results of the model ($customer->orders)


Associated result cache

If the order table changes at this time, We hope that if you query again


$user = $order->user;

you will find that there is no change when you get the order again. The reason is that the database will only be queried when $order->user is executed for the first time, and the results will be cached, and sql will not be executed during subsequent queries.

So what if you want to execute sql again? You can execute


//先释放缓存
unset($order->user);
$order->user;

Cross-table query

The following is the key point! As you can see from the table structure diagram above, the User table and Order_goods are not directly related. So if we want to find out which products the user bought based on user information, we must associate the two tables through the Order table. So what to do? The first is the model layer. Because we are checking based on the user, we go to the User model layer to define the association.

User

##

public function getOrder() {
 return $this->hasMany(Order::className(), ['user_id' => 'user_id']);
}
 
public function getOrderGoods() {
 return $this->hasMany(OrderGoods::className(), ['order_id' => 'order_id'])->
  via('order');
}

Note here: The second one in getOrderGoods order_id refers to the order_id in the Order associated with getOrder, and the first order_id refers to the order_id in OrderGoods. but! We also have the simplest method, which is to use SQL statements!

$map = 'select
  user.name,
  order.id,
  order_goods.goods_id,
  goods.goods_name,
  stock.stock_count
  from user
  LEFT JOIN order   ON order.user_id = user.user_id
  LEFT JOIN order_goods ON order_goods.order_id = order.order_id
  LEFT JOIN goods   ON goods.goods_id = order_goods.goods_id
  LEFT JOIN stock   ON stock.goods_id = goods.goods_id';

$list1 = Article::findBySql($map)->asArray()->all();

This is basically the entire related part

Summary

The above is the detailed content of Detailed examples of how to operate multi-table associations in YII2. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools