Rohullah Rajaee Rad
Rohullah Rajaee Rad

Reputation: 581

How to implement this relationship in laravel?

i have 4 table

inst
   id
   subject

report
   id
   subject

 object
   id
   type

 container
    id
    obj_id

i want with obj_id of container table, achieve the The corresponding object record. then if type of object = 1, fetch data from inst table or type = 2, fetch data from report table

Upvotes: 0

Views: 133

Answers (2)

ZeroOne
ZeroOne

Reputation: 9117

based on your information,

you can do like @Mahfuz Shishir answer

or

create new appends attribute inside Object Model

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
     }
}

Upvotes: 1

Mahfuz Shishir
Mahfuz Shishir

Reputation: 841

The relation looks like.

In your Object.php Model

public function containers()
{
    return $this->hasMany('App\Container', 'foreign_id');
}

And in your Container.php Model

public function object()
{
    return $this->belongsTo('App\Object', 'foreign_id');
}

You provide little information. Implement rest of the controller code in your own sense. Or put some code that you have tried.

Upvotes: 0

Related Questions