I have a strange Laravel 9 setup due to being constrained to a very ancient database.
I’m trying to come up with a clean way to create a hasMany relationship to multiple models located in a folder. I believe it would be easiest explained with diagrams:
app/Models/
- Customer
app/Models/Records/
- Orange
- Green
- Blue
Now, all of these records has some connection to customer, but these are all different as well, for example, orange refers to customer using cid
, where Green might use customerid
.
I’ve already set up logic where every record model has a customer belongsTo relationship depending on the different field names.
public function customer()
{
return $this->belongsTo('AppModelsCustomer', 'CustomerId');
}
I need to create a records()
function in the Customer model, that pulls in all of these Records where found. I can’t create any new tables that would be stored on the DB.
2
Answers
None of these solutions quite achieved what I was looking for in terms of simplicity, and in my case my database is quite out of date and slow, so I ended up landing on a solution that is quite simple and faster than everything posted for my use case:
This achieves what I was looking for in terms of setting up the relationships when the customerId field was subject to change on the other tables, and is pretty readable overall.
For multiple tables (models) to be connected as hasMany is probably not possible out of the box in Laravel.
However if you do really need to combine them all, I did once but it is not pretty.
First add following to each of your AppRecordsModel in example is Green
And now for the Customer model
So now you can do
And inside your blade you can access them
A collection can be filtered and sorted
The only problem here is the records id where Orange can have the same id as Green and Blue.
Best is to add new field into Orange Green and Blue
$table->uuid('record_id')->nullable();
Hope this can help you out.