我正在扩展rainlab.user
插件,以允许每个用户通过一个包含以下字段的简单中间表与朋友联系:
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_id
的{{1}}传递给此范围。
答案 0 :(得分:3)
将当前模型作为第一个参数传递给视图和管理选项中提供的范围方法。我已经更新了文档以反映这一事实。
举个例子,您的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);
});
});