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
You can use the
hasOne
relationship to define that each instance of ModelC has one instance of modelA and modelB.You can use ModelC as if it’s a regular Eloquent model and access attributes from modelA and modelB directly.
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: