skip to Main Content

I would create a virtual model modelC (with no real table on the DB) as join between model modelA and model modelB. My need is to access to model modelC like a standard model and access to his attributes (modelA and modelB atributes) without accessit to them like

ModelC::find(1)->modelA->atribute_of_modelA 

but accessing to them like

ModelC::find(1)->attribute_of_modelA.

How can I implement this?

2

Answers


  1. You can use the hasOne relationship to define that each instance of ModelC has one instance of modelA and modelB.

    namespace App;
    
    use IlluminateDatabaseEloquentModel;
    
    class ModelC extends Model
    {
        protected $table = null; // No table associated with ModelC
    
        public function modelA()
        {
            return $this->hasOne(ModelA::class);
        }
    
        public function modelB()
        {
            return $this->hasOne(ModelB::class);
        }
    }
    

    You can use ModelC as if it’s a regular Eloquent model and access attributes from modelA and modelB directly.

    $modelC = ModelC::with('modelA', 'modelB')->find(1);
    
    $attributeOfModelA = $modelC->modelA->attribute_of_modelA;
    $attributeOfModelB = $modelC->modelB->attribute_of_modelB;
    
    Login or Signup to reply.
  2. First of all, to me, your request is absolutely unnecessary. You already got access to ModelA and ModelB with all their data. If possible, can you pls update your question sharing the context why you need to do so?

    If you still insist on doing so. You could create a view in your db that joins ModelA and ModelB together, name it model_cs table. That could be wired to the modelC model.

    Alternatively, and this is something I don’t highly recommend, you can use Laravel Sushi. So you can hydate your ModelC this way:

    use IlluminateDatabaseEloquentModel;
    use SushiSushi;
    
    class ModelC extends Model
    {
        use Sushi;
    
        public function getRows()
        {
            return ModelA::join('model_b', ...)
                ->get()
                ->toArray();
        }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search