如何从users表中检索userID?

时间:2016-04-13 05:52:18

标签: php mysql laravel laravel-5.2

我有一个名为用户个人资料的两个表。在个人资料表格中有一个名为userID的列。现在我希望此userID列从用户表的id获取值。我已经完成了数据库关系部分。但是无法通过视图检索数据。我已经搜索过,但根据我的问题我没有找到任何令人满意的答案。

顺便说一句,我是Laravel的新手。到目前为止我已经尝试了

用户模型:

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');
   }
}

我正在尝试使用userID检索{{$profile->userID}}。我真的不知道问题出在哪里以及如何做到这一点?

2 个答案:

答案 0 :(得分:2)

你需要告诉laravel获得像这样的关系模型

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

编辑: 来自docs

  

自动假设模型具有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');
}

答案 1 :(得分:0)

请将userID添加到可填写的个人资料数组中。

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

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