$topics = Post::find()->with('user', 'category')->limit(20)->where(['status' => 2])->orderBy(['created_at' => SORT_DESC])->all();
看到群主的代码里面有用到with()的方法, 发现这个方法大家用的蛮多的。希望能发个帖子,大家一起总结一下with()的用法
我先说一点,大家可以回复补充下总结哈。
with() 就是together的意思
Post这个类里面 要有 getUser() getCategory() 这个2个方法,这样就可以返回了组装在一起的数据了了。
下面是文档给出的3个example 哈哈哈
// find customers together with their orders and country
Customer::find()->with('orders', 'country')->all();
// find customers together with their orders and the orders' shipping address
Customer::find()->with('orders.address')->all();
// find customers together with their country and orders of status 1
Customer::find()->with([
'orders' => function (\yii\db\ActiveQuery $query) {
$query->andWhere('status = 1');
},
'country',
])->all();
You can call with()
multiple times. Each call will add relations to the existing ones.
For example, the following two statements are equivalent:
Customer::find()->with('orders', 'country')->all();
Customer::find()->with('orders')->with('country')->all();
首先帮你优化了一下排版,以后要注重排版。
然后我来回答你的这个问题吧,要想知道 with()
的用法,你先要了解 Yii 的 hasOne
和 hasMany
用法,相关知识你可以看文档的 Working with Relational Data。
而 with()
呢,其实是为了 延迟加载和预先加载,说白了 ->with('user', 'category')
就是去找 POST Model 里面的 getUser()
和 getCategory()
方法。
不要因为文档是英文就不看了,就算看代码你也可以看懂很多,这个页面至少你要看三遍,因为这个算是 Yii 的核心功能。