3

特定の列値を持つ AR に関連する ActiveRecordを選択する必要があります。

状況: 「ユーザー」には多くの「ブランチ」がある可能性があります - ジャンクション テーブルを介して、ブランチは部門に関連付けられています。私は を持っておりdepartment_id、この 1 つの部門からブランチを持つユーザーを選択したいと考えています。

デパートメント:

... $this->hasMany(Branch::className(), ['department_id' => 'id']);

ブランチ:

... $this->hasMany(User::className(), ['id' => 'user_id'])
                ->viaTable('{{%user_to_branch}}',['branch_id' => 'id']);

問題は、Department からこれにアクセスしたくないということです (例: $department->getUsers()....) ActiveQuery

したがって、次のようなユーザーを選択できます。

User::find()->fromDepartment(5)->all();

前もって感謝します !

4

2 に答える 2

0

ActiveRecord では:

/**
 * @inheritdoc
 * @return MyActiveRecordModelQuery the active query used by this AR class.
 */
public static function find()
{
    return new MyActiveRecordModelQuery(get_called_class());
}

MyActiveRecordModelQuery:

/**
 * @method MyActiveRecordModelQuery one($db = null)
 * @method MyActiveRecordModelQuery[] all($db = null)
 */
class MyActiveRecordModelQuery extends ActiveQuery
{
    /**
     * @return $this
     */
    public function fromDepartment($id)
    {
        $this->andWhere(['departament_id' => $id]); //or use relation

        return $this;
    }
}

使用法:

MyActiveRecordModelQuery::find()->fromDepartment(5)->all();
于 2015-10-08T14:30:37.280 に答える
-1

ユーザーモデル方式

public function getBranch()
{
    return $this->hasMany(Branch::className(), ['id' => 'branch_id'])
                ->viaTable('{{%user_to_branch}}', ['user_id' => 'id']);
}

public static function fromDepartment($id)
{
    $query = self::find();
    $query->joinWith(['branch'])
          ->andWhere(['department_id'=>$id]);
    return $query->all();
}

使用法:

User::fromDepartment(5);
于 2015-10-08T14:32:59.983 に答える