问题
I need to display only those records in the model that are attached to some groups. ("belongsToMany" Relations). (backend page of plugin list of Movies model) I want to get the groups of the current user and create a query.
What I mean:
I use Relations field to to attach records to groups.
i.e:
- I have table "elisseii_myplugin_movies".
- In the "Movies" model, I created a relation field with the name "groups".
- and created the table "elisseii_myplugin_movies_groups".
Used $belongsToMany in the "Movies" model.
public $belongsToMany =[ 'groups' =>[ 'Elisseiidev\MyPlugin\Models\Groups', 'table' => 'elisseii_myplugin_movies_groups', 'order' => 'name' ] ];
The "Groups" model in the plug-in uses the standard table "backend_user_groups".
Now records have information about the groups attached to them. You can see the video tutorial, which says about it)
I need that users can not edit records that do not belong to their group. It is necessary that the code be dynamic.
I need a detailed answer, since I'm learning)) Thank you in advance for your time.
回答1:
you need to add this method to the controller which is using list behaviour means shows the lists.
public function listExtendQuery($query) {
$user = \BackendAuth::getUser();
$codes = $user->groups->pluck('code')->toArray();
$query->whereHas('groups', function ($q) use ($codes){
$q->whereIn('groups.code', $codes);
});
}
this listExtendQuery
method will extend query with our custom condition for list which is showed for user.
here we fetch Be user then we extract code
as it will be array, user can have multiple groups.
now your Movies
table has groups
relation so it can have multiple groups so now we can check that if that movies group code is available in user then we can show him list item.
infect you don't need to create new model(Elisseiidev\MyPlugin\Models\Groups
) you can directly use in-built Model if you don't need additional functionality.
you can simpally do like
public $belongsToMany = [
'groups' => [
Backend\Models\UserGroup::class,
'table' => 'elisseii_myplugin_movies_groups',
'order' => 'name'
]
];
let me know if it works or not.
来源:https://stackoverflow.com/questions/47888265/october-cms-display-only-those-records-that-are-attached-to-the-groups-of-the