[英]laravel model relationships hasOne
我有兩個表,第一個是用於身份驗證的帳戶(用戶模型),另一個是學生(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;
原因是我的關系,但我不確定這有什么問題
您應該修改它:
$application->S_ID= Auth()->User()->students->S_ID;
在用戶模型中,您必須在hasOne函數的第二個參數中添加foregnkey,因此用ex的S_ID替換Account_ID:
// in user model
public function students()
{
return $this ->hasOne('App\t_student', 'S_ID');
}
// in ur controller romove the parentheses of students propriety
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.