OctoberCMS:如何在关系配置文件中动态过滤 manage.list

OctoberCMS: How to dynamically filter manage.list in relation configuration file

我正在扩展 rainlab.user 插件以允许每个用户通过一个简单的中间体 table 拥有以下字段的朋友:

user_id
friend_id
status

因此,我扩展了 Rainlab.User Controller 以具有 Friends 选项卡,其中列出了用户的所有朋友:

use RainLab\User\Models\User as FrontUser;
use RainLab\User\Controllers\Users as UsersController;

FrontUser::extend(function($model) {
    $model->belongsToMany['friends']=[
        'RainLab\User\Models\User',
        'table'    => 'meysam_social_friends',
        'pivot' => ['status'],
        'key'      => 'user_id',
        'otherKey' => 'friend_id'
    ];
});

UsersController::extend(function($controller) {
    if(!isset($controller->implement['Backend.Behaviors.RelationController'])) {
        $controller->implement[] = 'Backend.Behaviors.RelationController';
    }
    $controller->relationConfig  =  '$/meysam/social/controllers/user/config_relations.yaml';
});

UsersController::extendFormFields(function($form, $model, $context) {
    if(!$model instanceof FrontUser or $context != 'preview'){
        // friends tab should not be displayed in update and create contexts
        return;
    }

    $form->addTabFields([
        'friends' => [
            'label' => '',
            'tab' => 'Friends',
            'type' => 'partial',
            'path' => '$/meysam/social/controllers/user/_friends.htm',
        ]
    ]);
});

这里是 config_relations.yaml 文件:

friends:
    label: 'new friend'
    view:
        list: ~/plugins/meysam/social/models/friendspivot/columns.yaml
        toolbarButtons: add|remove
        showSearch: true
    manage:
        showSearch: true
        recordsPerPage: 10
        list: ~/plugins/rainlab/user/models/user/columns.yaml
    pivot:
        form: ~/plugins/meysam/social/models/friendspivot/fields.yaml

现在在好友选项卡中,会显示当前所选用户的好友列表,当我单击 Add new friend 按钮时,会显示所有用户的列表 (manage.list),以便其中一个用户可以被选为新朋友。我的问题是,在此列表中,显示了所有用户,甚至包括当前选定的用户,因此可以将用户添加为他自己的朋友。如何从此列表中过滤掉当前用户?我想过使用 scope 属性 但是这个范围应该是动态的,我不知道如何将当前 User Modeluser_id 传递给这个范围。

当前模型作为第一个参数传递给视图和管理选项中提供的范围方法。我已经更新了文档以反映这一事实。

举个例子,你的 config_relation.yaml 应该是这样的

friends:
    label: 'new friend'
    view:
        list: ~/plugins/meysam/social/models/friendspivot/columns.yaml
        toolbarButtons: add|remove
        showSearch: true
    manage:
        showSearch: true
        recordsPerPage: 10
        list: ~/plugins/rainlab/user/models/user/columns.yaml
        scope: notThis
    pivot:
        form: ~/plugins/meysam/social/models/friendspivot/fields.yaml

然后应该将查询范围方法 notThis 动态添加到用户模型中:

FrontUser::extend(function($model) {
    $model->addDynamicMethod('scopeNotThis', function ($query, $user) {
        return $query->where('id', '!=', $user->id);
    });
});