问题
I'm attempting to do a basic query in Laravel by querying a table that holds polymorphic relationships. The table has a column called record_type
which holds values such as App\MedicationError
and App\PressureUlcer
.
I want to run a query similar to this:
`Action::where('record_type','App\MedicationError')`
I have a set of variables containing strings like MedicationError
and PressureUlcer
.
How would I go about prefixing those strings with App\
?
The reason I am having difficulty myself is I cannot work out how to add a backslash to the end of my 'App'
string. This is what I am trying at the moment:
$type = 'App\\ '.studly_case($record->type);
But it returns App\\ RiskAssessmentUpdate
. If I remove the space from the end the backslash obviously escapes the single quote. trim('App\\ ')
doesn't help either.
I feel like I'm missing a really obvious (regex?) solution here. Any help would be appreciated.
回答1:
Putting two backslashes together in a single quoted string should create a single backslash, the first one escapes the second.
$type = 'App\\' . studly_case($record->type);
Alternatively, you could use a double quoted string, in the same way:
$type = "App\\" . studly_case($record->type);
My guess is that your problem lies in the studly_case($record->type)
part of your code, in that it's returning a backslash at the beginning of it. Give this code a try and see if it works:
$type = "App\\" . ltrim(studly_case($record->type), '\\');
That should trim off any and all leading backslash characters.
来源:https://stackoverflow.com/questions/39327162/adding-a-backslash-to-the-end-of-a-php-string