【问题标题】:Yii2 efficiency - foreign key or anonymous function in view?Yii2 效率 - 外键还是匿名函数?
【发布时间】:2017-06-11 19:00:02
【问题描述】:

我使用外键从一个表中获取数据库值而不是另一个表,例如这个...

public function getAuthor() {
    return $this->hasOne(SiteUsers::className(), ['id' => 'authorId']);
}

... 或 CRUD 视图文件中的匿名函数,例如:

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'id',

            'hotel_id' => [
                'attribute' => 'hotel_id',
                'value' => function ($value) {
                    return \common\models\Hotels::find()
                    ->where(['id' => $value->hotel_id])
                    ->one()['name'];
                }
            ],

            'country_id' => [
                'attribute' => 'country_id',
                'value' => function ($value) {
                    return \common\models\Countries::find()
                    ->where(['id' => $value->country_id])
                    ->one()['name'];
                }
            ],

            'room_type',
            'max_persons',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

现在,问题是:一种方法比另一种更有效吗?为什么?

【问题讨论】:

    标签: php database performance activerecord yii2


    【解决方案1】:

    您必须记住,如果您使用 activeRecord,则无论如何都会执行关系 getAuthor(),并且这是针对 dataProvider 中涉及的每个模型执行的。

    一般来说,直接访问比基于 ORM 的访问更快。并且在渲染阶段执行的匿名函数访问基本上等同于关系执行的访问..最好的性能是基于避免ORM或activeRecord建模的直接命令。但这意味着失去了 ORM 授予的抽象级别。

    请记住,如果您同时拥有两者(关系一个匿名函数),您将执行两次查询..

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      • 2017-02-07
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多