【问题标题】:Yii2 relation based on attribute values instead of keysYii2 基于属性值而不是键的关系
【发布时间】:2020-01-12 22:57:40
【问题描述】:

我在 db (mysql) 中有 2 个表,在 2 个表之间没有通过键或 id 的经典关系。我可以定义关系的唯一方法是通过属性值。例如。表 wheelcar 和某些车轮仅因为尺寸而与某些汽车相匹配。是否可以在 DB 级别和/或 yii2 中定义,如果可以,如何定义?

在关系中,我可以添加一个 onCondition(),但你也可以定义一个属性 (???)

public function getWheels() {
    return $this->hasMany(\app\models\Wheel::className(), ['???' => '???'])->onCondition(['<', 'wheelsize', $this->wheelsize]);
}

我可以使用假属性并将其设置为所有记录,例如 1,但这对我来说似乎有点奇怪。

我在网上找不到任何关于此的内容,或者我只是在搜索错误的方式,或者我正在尝试一些完全不正确的做法。你能指出我正确的方向吗?

【问题讨论】:

    标签: yii2 database-relations


    【解决方案1】:

    我不认为你可以通过关系来实现这一点。 但是有一种方法可以解决这个限制。

    <?php
    
    namespace app\models;
    
    class Car extend \yii\db\ActiveRecord
    {
        /**
         * @var \app\models\Wheel
         */
        private $_wheels;
    
        /**
         * @return \app\models\Wheel[]
         */
        public function getWheels()
        {
            if (!$this->_wheels) {
                $this->_wheels = Wheel::find()
                    ->where(['<', 'wheelsize', $this->wheelsize])
                    //->andWhere()  customize your where here
                    ->all();
            }
    
            return $this->_wheels;
        }
    }
    

    然后你可以像访问关系一样访问wheels 属性。

    <?php
    
    $car = Car::find(1);
    $car->wheels;
    

    注意这种方式不支持Eager Loading

    【讨论】:

      【解决方案2】:

      假设您可以将空数组设置为链接,但出于安全原因(我认为)条件“0 = 1”会自动添加到选择中。

      我多次遇到您自己的问题,我能找到的最佳解决方案是明确使用 ActiveQuery(类似于 hasOne 和 hasMany 的情况):

      public function getWheels() {
          return new ActiveQuery(\app\models\Wheel::className(), [
              'where' => 'my condition' // <--- inserte here your condition as string or array
              'multiple' => true        // true=hasMany, false=hasOne
              // you can also add other configuration params (select, on condition, order by, ...
          ]);
      
      }
      

      这样可以同时获取数组和ActiveQuery来添加其他条件:

      var_dump($model->wheels);            // array of wheels objects
      var_dump($model->getWheels());       // yii\db\ActiveQuery object
      $model->getWheels()->andWhere(...);  // customize active query
      

      【讨论】:

      • 我从你的回答中得到了一些新的东西。不错的工作! :)
      • 您的解决方案也是一个不错的选择。很高兴有帮助:)
      猜你喜欢
      • 2017-05-03
      • 2016-10-08
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多