mysql - yii2 join ->with() 记录右表数据到模型

标签 mysql join activerecord yii2

关于项目中关系的问题。这是我得到的: 我有一个主表 {{%page}} 和一个使用它的模型页面。它包含 View 中将来动态使用的所有数据。 我还有一个表 {{%file}},其中包含特定页面的文件。关键是“builder_id”列。我在“页面”中创建了模型之间的关系

 `public function getFiles() {
        return $this->hasMany(File::className(),['builder_id' => 'builder_id']);  

    }`

在"file"中

public function getPage() {
        return $this->hasOne(Page::className(), ['builder_id' => 'builder_id']);

    } 

目标:使用此方法获取页面模型时:

public static function getPageById ($builder_id = 1) {
        $model = Page::find()->where(['builder_id' => $builder_id])->one();

        if ($model === null) {
            throw new NotFoundHttpException("Error.");
        }

        return $model;
    } 

将页面文件也记录到模型中,其中 builder_id 相同。为此,我使用了 ->with(),它使 Page 方法如下:

public static function getPageById ($builder_id = 1) {
        $model = Page::find()
                ->with('file')
                ->where(['builder_id' => $builder_id]);

        if ($model === null) {
            throw new NotFoundHttpException("Error.");
        }

但在模型中,我既没有得到第一个表数据,也没有得到第二个表数据。模型的 Vardump 给出了这个

object(yii\db\ActiveQuery)#64 (27) { ["sql"]=> NULL ["on"]=> NULL ["joinWith"]=> NULL ["select"]=> NULL ["selectOption"]=> NULL ["distinct"]=> NULL ["from"]=> NULL ["groupBy"]=> NULL ["join"]=> NULL ["having"]=> NULL ["union"]=> NULL ["params"]=> array(0) { } ["_events":"yii\base\Component":private]=> array(0) { } ["_behaviors":"yii\base\Component":private]=> array(0) { } ["where"]=> array(1) { ["builder_id"]=> string(1) "2" } ["limit"]=> NULL ["offset"]=> NULL ["orderBy"]=> NULL ["indexBy"]=> NULL ["modelClass"]=> string(15) "app\models\Page" ["with"]=> array(1) { [0]=> string(5) "files" } ["asArray"]=> NULL ["multiple"]=> NULL ["primaryModel"]=> NULL ["link"]=> NULL ["via"]=> NULL ["inverseOf"]=> NULL }  

我做错了什么?

最佳答案

请务必在查询后调用one()all()

public static function getPageById ($builder_id = 1) {
    $model = Page::find()
            ->with('files') // here is you typo. You defined relationship with files and accessing it through file.
            ->where(['builder_id' => $builder_id])
            ->one(); // this line will return result.

    if ($model === null) {
        throw new NotFoundHttpException("Error.");
    }

在你的例子中,你没有对 ActiveQuery 对象做任何事情。 您需要在查询对象上调用 all() 或 one() 以获得结果

关于mysql - yii2 join ->with() 记录右表数据到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530262/

相关文章:

ruby-on-rails - Rails/ActiveRecord 实现 "Watch list"关系

php - LIMIT 1 对于顶级表WITH JOIN

mysql - 更新数据库结构 - 新表或添加字段

MySQL查询根据特定条件从多个表中选择

ruby-on-rails - rspec 中的多线程 ActiveRecord 请求

ruby-on-rails - rails 3 : Get Random Record

mysql - 观察数据库中条目的年龄并触发事件

jquery - 无法将数据从表单发送到 SQL 数据库

mysql - 关联表中某个字段的计数和如何获取?

mysql - 使用连接从表中获取最新值