如果您设置了User.php return $this->belongsTo('App\User');
和Profile.php return $this->hasOne('App\Profile', 'user_id', 'id');
之间的关系,当您仅获取Profile变量时,如何才能将相应的用户获取到Profile。 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');
}
答案 0 :(得分:2)
您的位置格式不正确。您需要传入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);
答案 1 :(得分:1)
您可以通过某些方式来做到。
解决方案1:
User::whereId($profile->user_id)->first();
解决方案2:
User::where('id', $profile->user_id)->first();
解决方案3:
User::where('id','=', $profile->user_id)->first();
解决方案4:
User::where(['id' => $profile->user_id])->first();
您也可以做到 在Profile模型中定义
public function user()
{
return $this->belongsTo('App\User');
}
比你可以懒加载
$user = $profile->load('user')->user; // but it is lazy loading