我使用 Angular 进行前端工作,并且我想使用 Laravel 执行 CRUD 我有两个表用户和学生,学生表有一个引用用户表的外键。 我想插入来自一种表单的数据,我尝试了这个:
学生模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Etudiant extends Model
{
protected $table = 'students';
protected $primaryKey = 'idStudent';
public $timestamps = false;
protected $fillable = [
'dateNaissance',
'filier',
'niveauEtude',
'cne',
'specialite'
];
public function user(){
return $this->belongsTo(\App\Models\User::class);
}
use HasFactory;
}
用户模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Utilisateur extends Model
{
protected $table = 'users';
protected $primaryKey = 'idUser';
public $timestamps = false;
protected $fillable = [
'nom',
'prenom',
'password',
'email',
'numTel'
];
public function student(){
return $this->hasMany(\App\Models\Student::class);
}
use HasFactory;
}
学生控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Users;
use App\Models\Student;
class StudentController extends Controller
{
protected $student;
protected $user;
protected $studentData;
protected $userData;
public function __construct(){
$this->student = new Student();
$this->user = new Utilisateur();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$studentData = array_diff_key($request->all(), array(['nom', 'prenom', 'password', 'email', 'numTel']));
$userData = array_diff_key($request->all(), array(["dateNaissance", "filier", "niveauEtude", "cne", "specialite"]));
$this->user->student()->create($userData);
$this->student->user()->create($studentData);
return [];
}}
我得到的错误
未找到列:1054“字段列表”中未知列“utilisateur_idUser”(连接:mysql,SQL:插入
etudiant
(dateNaissance
,filier
,niveauEtude
,cne
,specialite
,) utilisateur_idUser
)值(12/12/12,mip,bac+3,m130118922,MA,?))
当您使用关系
$this->user->student()
时,utilisateur_idUser
是自动生成的列名称来搜索学生和用户之间的关系,也就是说,您的学生表需要有一列来引用用户默认情况下,Laravel 希望它以父模型 + _
+ 父主键命名。如果你的students表中的外键名称不同,你需要在声明关系时显式定义它:
public function student(){
return $this->hasMany(\App\Models\Student::class, 'fk_in_students_table_referring_to_the_users_table');
}
现在,要完成您想要的任务,您需要首先创建您的用户,例如:
$this->user->fill(...)->save();
,然后使用您的用户创建相关的学生,例如:$this->user->students()->create(...);
此外,如果您的用户只需要链接一名学生,则正确的关系应该是
->hasOne()
而不是 ->hasMany()
Arr::only($request->all(), ['key1', ...])