laravel - Laravel:在字符串上调用带有()的成员函数
问题描述
因为我还是初学者,所以我在 Laravel 上苦苦挣扎。在我的web.php
我有以下路线
Route::get('/customize/{id}', function ($id) {
if (User::where('id','=','4')->has('profile'->with('id',$id))->exists() && Profile::where('user_id', $id)->exists()) {
return true;
}
return false;
});
我知道有些不对劲。
基本上我想要做的是,仅当具有4的用户的个人资料与url 中的个人资料相同时才返回 true。id
id
在我的用户模式中,我有以下关系:
public function profile()
{
return $this->hasMany(Profile::class);
}
配置文件表示例:
解决方案
你有一个错字。
if (User::where('id','=','4')->has('profile'->with('id',$id))->exists() && Profile::where('user_id', $id)->exists()) {
应该
if (User::where('id','=','4')->has('profile')->with('id',$id)->exists() && Profile::where('user_id', $id)->exists()) {
通过这样做'profile'->with(...)
,您正在调用with(...)
字符串 () 上的成员函数 ( 'profile'
)。
仅当 ID 为 4 的用户的个人资料 ID = $id 时才返回true
,您想使用whereHas
.
if (
User::where('id', 4)->whereHas('profile', function ($query) use ($id) {
return $query->where('id', $id);
})
->exists()
) { ... }
使用 PHP ^7.4,这可以用简写闭包更紧凑地编写。
if ( User::where('id', 4)->whereHas('profile', fn($query) => $query->where('id', $id))->exists() ) { ... }
顺便说一句,在使用 时where()/orWhere()
,如果不使用运算符,则默认为'='
sowhere('id', '=', 4)
可以写为 just where('id', 4)
。
推荐阅读
- sql - 为什么我在 pl/sql 的 for 循环中得到这个 group-by 错误?
- java - 接收 null Parcelable 对象 Android
- wpf - 如何在 mvvm 中获取文本块的值
- reactjs - 反应不从 docker 容器发出请求
- swift - SwiftUI:从另一个初始化程序调用它时,如何让我的闭包返回“内容”而不是“某些视图”?
- excel - VBA粘贴剪贴板内容(唯一值)
- html - 如何在不加倍边框或使用边框折叠的情况下圆桌边框?
- macos - 检测主机是否可以通过跳转主机访问
- java - Spring QueryDsl 分页过滤器按 ACL 权限
- windows - 在 Windows 10 中启用剪贴板历史记录