Yii2 Active Record:显示相关记录的最佳方法

最后发布: 2015-10-23 13:04:23


问题

我有两个表: recorduser和一个联结表record_user 我使用活动记录显示与登录用户相关的记录。

在模型用户中,我具有以下功能:

public function getRecordUsers()
{
    return $this->hasMany(RecordUser::className(), ['user_id' => 'id']);
}

public function getRecords()
{
    return $this->hasMany(Record::className(), ['id' => 'record_id'])
        ->via('recordUsers');
}

请参阅: http : //www.yiiframework.com/doc-2.0/guide-db-active-record.html#junction-table

在RecordSearch模型中,我为Active Data Provider定义查询:

public function search($params)
{

// The Object with all records, to which has the user access (the id of the user is in the junction table record_user).
$loggedUserRecords = YiiUser::findOne(Yii::$app->user->identity->id)->records;

// From the object is extracted an array with ids.
$loggedUserRecordsIds = yii\helpers\ArrayHelper::getColumn($loggedUserRecords, 'id');

// The ids are used to filter the Record object.
$query = Record::find()->filterWhere(['id' => $loggedUserRecordsIds]);

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);
...

该代码按预期工作。 但是我想知道,是否有一种更直接的方式来显示相关记录,而无需从对象中提取ID。

yii yii2
回答

我想RecordSearch有这种关系

public function getRecordUsers()
{
    return $this->hasMany(RecordUser::className(), ['record_id' => 'id']);
}

public function getUsers()
{
    return $this->hasMany(User::className(), ['id' => 'user_id'])
    ->via('recordUsers');
}

要么

public function getUsers()
{
    return $this->hasMany(User::className(), ['id' => 'user_id'])->viaTable('recordUsers', ['record_id' => 'id']);
}

那么您应该能够检查类似以下内容的查询:

$dataProvider = new ActiveDataProvider([
    'query' => Record::find()->joinWith(['users'])->where(['user_id'=> Yii::$app->user->identity->id]),
]);

如果我没有记错的话。


回答

正如BHoft所建议的那样,最快和最简单的方法可能是以下方法。

型号记录:

public function getRecordUsers()
{
    return $this->hasMany(RecordUser::className(), ['record_id' => 'id']);
}

型号记录搜索:

$dataProvider = new ActiveDataProvider([
    'query' => Record::find()->joinWith(['recordUsers'])->where(['user_id'=> Yii::$app->user->identity->id]),
]);