如何在laravel中实现这种关系?
我有4张桌子如何在laravel中实现这种关系?,laravel,polymorphism,relationship,Laravel,Polymorphism,Relationship,我有4张桌子 inst id subject report id subject object id type container id obj_id 我想用容器表的obj_id,实现相应的对象记录。 然后,如果对象类型=1,则从inst表中获取数据;如果对象类型=2,则从报告表中获取数据,则关系如下所示 在Object.php模型中 public function containers() { return $this-&
inst
id
subject
report
id
subject
object
id
type
container
id
obj_id
我想用容器表的obj_id,实现相应的对象记录。
然后,如果对象类型=1,则从inst表中获取数据;如果对象类型=2,则从报告表中获取数据,则关系如下所示 在Object.php模型中
public function containers()
{
return $this->hasMany('App\Container', 'foreign_id');
}
public function object()
{
return $this->belongsTo('App\Object', 'foreign_id');
}
在Container.php模型中
public function containers()
{
return $this->hasMany('App\Container', 'foreign_id');
}
public function object()
{
return $this->belongsTo('App\Object', 'foreign_id');
}
你提供的信息很少。在您自己的意义上实现控制器代码的其余部分。或者输入一些您尝试过的代码。基于您的信息 你可以像@Mahfuz Shishir那样回答 或 在对象模型内创建新的“附加”属性
protected $appends = ['data'];
public function getDataAttribute()
{
if($this->attributes['type'] == 1) {
return Inst::where('inst_column', $this->attributes['object_column_to_match']); //this just sample
} else {
return Report::where('inst_column', $this->attributes['object_column_to_match']); //this just sample
}
}
信息太少,请详细描述您试图实现的目标?