In my Plugin I have a User Dropdown. My Model has a belongs to one with a scope to only show Users with a certain Group. I have extended the User Plugin Model with a scope function.
I expect that the Relationship field to only display the users returned from the scope.
if I dd the query I am using the array returned doesn't include users without the "DJ Group" Group.
The User Dropdown has all users.
Plugin.php
User::extend(function(User $model){
$model->hasOne['dj'] = ['\JohnMainDesigns\djs\Models\dj'];
});
User::extend(function($model){
$model->addDynamicMethod('scopeGroup',function($query){
$djgroup = 'DJ Group';
return (array) User::join('users_groups','users_groups.user_id','=','users.id')->join(
'user_groups','users_groups.user_group_id','=','user_groups.id'
)->where(
function($query) use ($djgroup){
$query->where('user_groups.name', '=',$djgroup);
})->get();
});
});
DJ.php
public $belongsTo = [
'user' => ['\RainLab\User\Models\User',
'scope' => 'group']
];
428
@johnmain please put code blocks in code markdown tags (three backticks).
What is the field config for your user dropdown?
fields:
excerpt:
label: Excerpt
size: large
oc.commentPosition: ''
span: full
type: textarea
page_body:
label: 'Page Body'
size: large
oc.commentPosition: ''
span: full
type: textarea
user:
label: User
oc.commentPosition: ''
nameFrom: name
descriptionFrom: description
span: auto
type: relation
sort:
label: Sort
oc.commentPosition: ''
span: auto
default: '0'
type: number
Please paste the config from your fields.yaml file, not a screenshot of the builder plugin UI.
replaced image with yaml file contents
Instead of a Type of relation should I be using a partial and putting my filter logic in there?
I'm guessing that you are having problems because you aren't fully understanding how model scopes work. Model scopes are meant to modify and return the $query object, to be chained. They aren't meant to return records directly. Your scope should be filtering records that have a groups relationship with the required name:
$model->addDynamicMethod('scopeGroup', function($query) {
$djgroup = 'DJ Group';
return $query->whereHas('groups', function ($relationQuery) use ($djgroup) {
$relationQuery->where('name', $djgroup);
});
}
Ok that works. Thanks for the help.
Most helpful comment
I'm guessing that you are having problems because you aren't fully understanding how model scopes work. Model scopes are meant to modify and return the $query object, to be chained. They aren't meant to return records directly. Your scope should be filtering records that have a groups relationship with the required name: