我正在制作一些具有一对多关系的表,我也有一对一的关系,但是如果我解决了为什么它不起作用的原因,也许我也可以一对一地解决。我将提供一些代码供您查看。
当我去修补并键入"公司::find(1(->deparments"时,它返回 null。 当我检查数据库时,外键被正确添加。我还在模型中设置了主键。
公司表
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('company_id');
$table->string('phone');
$table->string('company_name',100);
$table->timestamps();
});
}
部门表
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('department_id');
$table->unsignedBigInteger('company_id');
$table->foreign('company_id')->references('company_id')->on('companies')->onDelete('cascade');
$table->string('department_name',100);
$table->timestamps();
});
}
公司模式
protected $primaryKey = 'company_id';
Protected $table='companies';
Protected $fillable=['phone','company_name'];
public function users()
{
return $this->hasMany(User::class,'user_id');
}
部门模型
protected $primaryKey = 'department_id';
protected $table = 'departments';
protected $fillable = ['department_name'];
public function company()
{
return $this->belongsTo(Company::class,'company_id');
}
public function users()
{
return $this->hasMany(User::class,'department_id');
}
您错过了公司模型中的部门关系,无法调用此命令。
public function departments()
{
return $this->hasMany(Department::class,'department_id');
}
我认为建立关系后应该是这样的,
Company::with(['deparments'])->findOrFail(1);
希望这对:)有所帮助