我有一些特定的数据库结构,如下图所示
因此,基本上一个零件可以具有多个规格,但是这些规格在已知表中不存在。规格可以在任何 rsnf_part_specification , rgr_part_specification 或 dcd_part_specification 表中。我需要找到一种方法来通过 part_owner_short_code FK来了解哪个表,因为它的规格表以 rsnf,dcd或rgr 为前缀。
是否可以使用Laravel 5.6口才关系做到这一点?
答案 0 :(得分:1)
您必须像这样修改表结构
owners(id, code, status)
parts(id, owner_id, category_id, name) //should add owner_id as FK
part_specifications(id, part_id, name, description) //no need to prefix owner code
所有者模型
class Owner extend Model {
protected $table = 'owners';
public function parts(){
return $this->hasMany('App\Part', 'owner_id');
}
public function partSpecification(){
return $this->hasManyThrough('App\PartSpecification', 'App\Part', 'owner_id', 'part_id');
}
}
零件模型
class Part extend Model {
protected $table = 'parts';
public function owner(){
return $this->belongsTo('App\Owner', 'owner_id');
}
public function category(){
return $this->belongsTo('App\Category', 'category_id'); // Define Category model
}
}
零件规格模型
class PartSpecification extend Model {
protected $table = 'part_specifications';
public function part(){
return $this->belongsTo('App\Part', 'part_id');
}
}
编辑:
如果要使用现有的规范结构,请尝试
所有者模型
class Owner extend Model {
protected $table = 'owners';
public function parts(){
return $this->hasMany('App\Part', 'owner_id');
}
}
零件模型
class Part extend Model {
protected $table = 'parts';
public function owner(){
return $this->belongsTo('App\Owner', 'owner_id');
}
public function category(){
return $this->belongsTo('App\Category', 'category_id'); // Define Category model
}
public function rnsPartSpecification(){
return $this->hasMany('App\RnsPartSpecification','part_id'); //define RnsPartSpecification model
}
public function rgrPartSpecification(){
return $this->hasMany('App\RgrPartSpecification','part_id'); //define RgrPartSpecification model
}
public function dcdPartSpecification(){
return $this->hasMany('App\DcdPartSpecification','part_id'); //define DcdPartSpecification model
}
}
获取数据
$parts = Part::with('owner', 'RsnfPartSpecification', 'RgrPartSpecification', 'DcdPartSpecification')->get();
foreach($parts as $part){
if($part->owner->code == 'rsnf'){
print_r($part->rnsPartSpecification)
}else if($part->owner->code == 'rgr'){
print_r($part->rgrPartSpecification)
}else{
print_r($part->dcdPartSpecification)
}
}