gpt4 book ai didi

php - Yii2 中的事件记录 (PHP) : access other DB tables with relations

转载 作者:行者123 更新时间:2023-11-29 19:43:10 25 4
gpt4 key购买 nike

我正在尝试在使用 Yii2 框架的项目中使用 Active Record 的关系数据功能。我在两个表(“post”和“result”)之间声明了多对多关系。当我尝试访问数据时,它以这种方式运行良好:

$post = Post::findOne(id);
$result= $post->result;

当我需要涉及第三个表时,我的问题就出现了。我(在我的模型中)声明了“结果”表和另一个表(“天气”)之间的多对一关系。

在结果 Controller 中:

public function getWeather() {
return $this -> hasOne(\modules\custom\models\Weather::className(), ['id' => 'weather_id']);
}

在天气 Controller 中:

public function getResult() {
return $this -> hasMany(\modules\custom\models\Result::className(), ['cube_id' => 'id']);
}

一旦我像上面提到的那样访问“帖子”和“结果”中的数据,是否也可以访问通过关系链接到“结果”的“天气”中的数据?如果没有,从第三个表获取数据的最佳方法是什么?

最佳答案

如果您使用 Post 模型作为查询中的主要模型,那么您必须在 Post 模型中创建关系。有两种情况:1.比如Post Model与Result和Weather模型有关系,那么你必须像这样编写查询

$post = Post::find()->joinWith(['result','weather'])->andWhere(['id'=>$id])->one;

2.如果 Post 模型仅与 Result 相关,而 Result 与 Weather 相关,则查询将如下所示:

$post = Post::find()->joinWith(['result','result.weather'])->andWhere(['id'=>$id])->one;

您可以在同一查询中添加多个关系。

关于php - Yii2 中的事件记录 (PHP) : access other DB tables with relations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41214835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com