php - 用户::where(user->id==$profile->id); 获取与控制器中的用户相同的配置文件
问题描述
如果您设置了之间的关系,那么当您仅获取配置文件变量时User.php return $this->belongsTo('App\User');
,Profile.php return $this->hasOne('App\Profile', 'user_id', 'id');
如何将相应的用户获取到配置文件。public function update(Request $request, Profile $profile)
我在想这样的事情,User::where(user->id==$profile->id);
但它不起作用你怎么能做到?
矿洞功能:
if(\Auth::check()) {
if(\Auth::user()->type == 'admin'){
$validated = $request->validate([
'username' => 'required',
'email' => 'required|email',
'firstname' => 'required',
'lastname' => 'required',
'age' => 'required|numeric|max:150',
'birthdate' => 'required|numeric',
'bio' => 'required|min:30',
'select_file' => 'image|mimes:jpg,png,gif,jpeg|max:2048'
]);
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$profile->username = $validated['username'];
$profile->email = $validated['email'];
$profile->firstname = $validated['firstname'];
$profile->lastname = $validated['lastname'];
$profile->age = $validated['age'];
$profile->birthdate = $validated['birthdate'];
$profile->bio = $validated['bio'];
$profile->image_path = $new_name;
$profile->update();
$user = User::where(user->id==$profile->id);
$user->name = $validated['username'];
$user->email = $validated['email'];
$user->update();
return redirect()
->route('admin')
->with('succes', 'Profile updated succesfully');
} else {
return redirect()
->route('admin')
->with('fail', 'Profile is unable to be update successfully');
}
} else {
return redirect()
->route('login')
->with('fail', 'Profile is unable to be update successfully
because ur not an Admin');
}
解决方案
您的 where 格式不正确。您需要传入 2 个(或 3 个)参数,其中第一个是列,第二个是您要检查的值。如果使用 3 个参数,则第二个是运算符(=
或!=
)。不要忘记first()
(对于一条记录)或get()
(对于一组记录),以便查询实际运行。否则,它将只是 QueryBuilder 对象。
User::where('id', $profile->user_id)->first();
或者
User::where('id','=', $profile->user_id)->first();
由于您正在检查用户的 id,因此您还可以使用find()
来获取一条记录:
User::find($profile->user_id);
推荐阅读
- vue.js - 如何将 element-ui 组件嵌入到 vuetify 组件中?
- charts - 不能在 Google 图表中使用带逗号的数字
- css - 从 CDN 引导下载或保存在本地
- javascript - 如何使用 getAttribute 传递组件中定义的值而不是 aframe 标签属性?
- java - 如何在 Vaadin 测试用例中为 GridElement 打开 GridDetail?
- wso2is - WSO2 IS 5.9.0 TOML,如何启用 SCIM2
- karate - 如何在数组中断言一个并不总是在响应中返回的值
- python - 是否使用一个类来存储多个函数所需的变量?
- javascript - 向 API 发送请求时反应失败
- sublimetext3 - Sublime Text 3 的 Liquidsoap 语法高亮