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

时间:2015-10-23 13:04:23

标签: yii yii2

我有两个表:记录用户和联结表 record_user 。我使用Active Record显示与记录用户相关的记录。

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

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。

2 个答案:

答案 0 :(得分:4)

我猜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]),
]);

如果我没有犯错。

答案 1 :(得分:1)

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

模型记录:

QImageReader

模型记录搜索:

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