首页 > 解决方案 > 用户::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');
    }

标签: phplaravellaravel-5.7

解决方案


您的 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);

推荐阅读