如何从users表中检索userID


How to retrive userID from users table?

我有一个名为usersprofile的两个表。在profile表中有一个名为userID的列。现在我希望这个userID列从users表的id中获取值。我已经做了数据库关系的部分。但无法使用视图检索数据。我已经搜索过了,但没有找到任何令人满意的答案。

顺便说一句,我在拉腊维尔是个新手。到目前为止,我已经尝试过

用户模型:

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table ="users";
    protected $fillable = [
        'userName', 'email', 'password',
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function userProfile(){
        return $this->hasOne('App'Profile');
    }
}

配置文件模型:

class Profile extends Model
{
    //
    protected $table = "profiles";
    public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
    public function user(){
        return $this->belongsTo('App'User');
   }
}

我正在尝试用{{$profile->userID}}检索userID。我真的不知道问题出在哪里,该怎么办?

您需要告诉laravel以获得类似的关系模型

$profile = Profile::find(1);
$userID  = $profile->user->id;

编辑:来自文档

模型被自动假定为具有user_id外键。

在您的情况下是userId,所以更改hasOnebelongsTo方法,告诉laravel您正在使用的foreign_key的名称

public function profile()
{
    return $this->hasOne('App'Profile', 'userId');
}
public function user()
{
    return $this->belongsTo('App'User', 'userId');
}

请将userID添加到配置文件的可填充数组中。

请检查下面的示例代码以执行相同操作。

public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic","userID"];