这是我的职责

public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

        return $data;
    }

新项目模型
public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }

它总是得到错误
message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669

请帮助我解决我的问题。

最佳答案

检查关系one-to-one reference
foreign_key user_id在newprojects表中,您需要建立如下关系:

用户模型:

public function newproject()
{
   return $this->hasOne(Newproject::class,'user_id');
}

新项目模型:

public function user()
{
   return $this->belongsTo(User::class);
}

10-08 20:16