请考虑以下情形:
程序包扩展了两个模型,这些模型之间的关系在程序包中定义。
例如,医生和患者:
App中的医生:
namespace App;
use SomePackage\Doctor as VendorDoctor
class Doctor extends VendorDoctor
{
(...)
}
应用程序中的患者
namespace App;
use SomePackage\Patient as VendorPatient
class Patient extends VendorPatient
{
(...)
}
供应商软件包中的医生:
namespace SomePackage;
class Doctor extends Model
{
public function patients()
{
return $this->hasMany(Patient::class);
}
}
供应商包装中的患者:
namespace SomePackage;
class Patient extends Model
{
public function doctor()
{
return $this->belongsTo(Doctor::class);
}
}
使用关系时将返回哪个模型?
示例:
$patient = \App\Patient::find($id);
$doctor = $patient->doctor;
$doctor
是App \ Doctor(具有该模型可用的功能)还是SomePackage \ Doctor?
答案 0 :(得分:1)
默认情况下为SomePackage\Doctor
。不过,您可以改写这种关系。
答案 1 :(得分:1)
由于SomePackage\Doctor
中的代码,默认情况下它将返回SomePackage
:
public function patients()
{
return $this->hasMany(Patient::class);
}
这里Patient::class
是一个特殊常量,包含指向Patient类的完整路径(带有名称空间)。它包含类似SomePackage\Patient
之类的东西,该路径属于包本身。因此,您不能仅通过使用另一个具有相同名称的类来更改它。
但是您可以redefine
类中的整个方法App\Doctor
。
namespace App;
use SomePackage\Doctor as VendorDoctor
class Doctor extends VendorDoctor
{
public function patients()
{
return $this->hasMany(\App\Patient::class);
}
}
之后,App\Doctor
将返回与App\Patient
的关系。
$doctor = \App\Doctor::find($id);
$patient = $doctor->patient;
//$patient containt Collection of App\Patient models
实际上,您甚至不需要定义完整的\App\Patient:class
路径,因为这里您已经在App
命名空间中,我只是添加了它以便更好地理解。