I have 3 models. User, role and service. The role is associated with the user, the user with the service. When adding a new entry to the service, I also want to add a user. Now it looks like this:
[
'label' => 'User',
'type' => 'relationship',
'name' => 'users',
'entity' => 'users',
'attribute' => 'name',
'ajax' => true,
'minimum_input_length' => 0,
],
Trait FetchOperation looks like this:
public function fetchUsers()
{
return $this->fetch([
'model' => Users::class,
'searchable_attributes' => ['name'],
'paginate' => 10,
'query' => function ($model) {
$search = request()->input('q') ?? false;
if ($search){
return $model->where('users.name', 'like', "%$search%");
}else{
return $model;
}
}
]);
}
It's work. I would like the search bar to display the role name and username for example: admin | John. But only the user name was added to the attribute. For example
public function fetchUsers()
{
return $this->fetch([
'model' => Users::class,
'searchable_attributes' => [],
'paginate' => 10,
'query' => function ($model) {
$search = request()->input('q') ?? false;
if ($search){
return $model->selectRaw('Concat(role.name," | ", users.name) as custom_value, users.name as name')
->leftJoin('role', ...)
->where('users.name', 'like', "%$search%");
}else{
return $model;
}
}
]);
}
CodePudding user response:
You can add an acessor in model like:
public function getRoleAndNameAttribute() {
return $this->role->name . '|' . $this->name;
}
And in your select define the attribute as attribute => 'roleAndName'
.
Edit: add it to your model $appends
property.
Cheers