laravel模型关系hasOne

时间:2018-12-28 03:51:06

标签: php laravel eloquent

我有两个表,第一个是用于身份验证的帐户(用户模型),另一个是学生(t_student模型),其中包含学生的详细信息,例如学生ID(S_ID)

我正在尝试为登录用户获取存储功能中控制器内的S_ID。

     $application = new Application;
     $application->A_ID= $request-> input('A_ID');
     $application->S_ID= Auth()->User()->students()->S_ID;
     $application->S_Justification= $request-> input('Justification');
     $application->save();
     return redirect('/Abstracts')->with ('success', 'application submitted' );

我的用户模型(帐户表)

class User extends Authenticatable{

protected $table = 'accounts';
protected $primaryKey = 'Account_ID';

use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
     'email', 'password', 'Account_Type', 'name'
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
public function abstracts(){
    return $this ->hasMany('App\Project' , 'PI_ID');
}
public function academics(){
    return $this ->hasOne('App\T_user', 'Account_ID');
}
public function students(){
    return $this ->hasOne('App\t_student', 'Account_ID');
}}

我的学生模型

class t_student extends Model{
protected $table = 't_student';
protected $primaryKey = 'S_ID';

public function account(){
return $this ->belongsTo('App\User', 'Account_ID');}

我收到此错误

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$S_ID

编辑:我遇到的错误与控制器有关

         $application->S_ID= Auth()->User()->students()->S_ID;

原因是我的恋爱关系,但我不确定这是怎么回事

2 个答案:

答案 0 :(得分:2)

您应该对其进行修改:

$application->S_ID= Auth()->User()->students->S_ID;

答案 1 :(得分:0)

在用户模型中,您必须将foregnkey添加到hasOne函数的第二个参数中 所以用S_ID替换Account_ID 例如:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let nextTag = textField.tag + 1

        if let nextResponder = textField.superview?.viewWithTag(nextTag) {
            nextResponder.becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }


        return false
    }