【问题标题】:Data value retrieve is not the same as in database - Laravel数据值检索与数据库中的不同 - Laravel
【发布时间】:2019-08-02 13:43:47
【问题描述】:

我创建了 3 个表。用户、学生和讲座。根据用户表上的类型,用户可以是学生或讲座。学生类型 =“std”,而讲座类型 =“lct”。问题是,当我作为讲座登录时,类型值将始终为“std”,即使在数据库中它是“lct”。 Laravel 中的新功能。谢谢

用户表

user_id    |  password  |   type  
a123       |   1234     |   std     
b345       |   1234     |   lct    

学生桌

student_id |   name
a123       |   david

讲台

lecture_id |   name
b345       |   Mr Steve

用户模型

protected $primaryKey = 'user_id';
public function student(){

    return $this->hasOne(student::class,'student_id');
}
public function lecture(){

    return $this->hasOne(lecture::class,'lecture_id');
}

Student 模型(Lecture 模型也有这个,但是 PK = Lecture_id)

protected $primaryKey = 'student_id';
public function User()
{
    return $this->belongsTo(User::class,'user_id');
}

HomeController

public function index()
{   
    $type = Auth::user()->type;
    dd($type);
}

【问题讨论】:

  • 你能说明你是如何将它们保存在你的用户表中的吗?
  • @TheodoryFaustine 我将它们注册到 register.blade.php 并且 registercontroller 会将它们插入到数据库中。我不认为这是我注册时的问题,插入到数据库中的数据是正确的。
  • dd($type); 的输出是什么?
  • 在您的每个关系中,您都应该为模型提供正确的路径,例如 hasOne('App\Phone')
  • 这个Auth::user() 只会为经过身份验证的用户或登录的用户返回?当前用户是 Lecture 吗?

标签: php mysql laravel model


【解决方案1】:

检查这个。只是假设

protected $primaryKey = 'user_id';
public function student(){

    return $this->hasOne(Student::class,'student_id'); // It should be Student not student I guess (Capital S)
}
public function lecture(){

    return $this->hasOne(Lecture::class,'lecture_id'); // Lecture not lecture
}

检查你的模型类名一次。

【讨论】:

  • 试过了,还是一样。班级名称是小写字母btw
猜你喜欢
  • 2018-05-24
  • 2018-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 2018-09-19
  • 2013-05-15
  • 2021-09-24
相关资源
最近更新 更多