0

I have 4 tables:

Table_A
  - id
  - sth

Table_B
  - id
  - a_id
  - sth

Table_C
  - id
  - b_id
  - sth

Table_D
  - id
  - c_id
  - sth

The relationships are as followed

Table_A <- Table_B (One to Many)
Table_B <- Table_C (One to Many)
Table_C <- Table_D (One to Many)

In order to access Table_C and Table_D from Table_A I used a hasManyThrough relationship for C and D. So now I pass a_id, b_id and c_id on GET because and I want to check if the relation between them exists.

First I tried this:

Table_A::with('Table_B.Table_C.Table_D')

The problem is I don't know how I can pass ids for each of the tables and I'm not sure if it will work, I would like to know if this can work or if there is a better way to check these relationships exist.

HelloSpeakman
  • 810
  • 9
  • 22
crowley
  • 23
  • 3
  • 1
    You should be able to check the relationship easily with Eloquent. `$model->relationship->count()` or `count($model->relationship)`. – HelloSpeakman Feb 19 '18 at 17:11
  • 1
    For your problem there should be something on Laravel to solve your problem in efficient way. But a way that i can think right now is fetching via table A. `count($table_a_data->table_b)` and then if count positive then `count ($table_a_data->table_b->table_c)` and `count($table_a_data->table_b->table_c->table_d)`. This will work for proper relationship. But the thing is this will increase your execution time if you have operations for each record in a relation. – BetaDev Feb 19 '18 at 17:14
  • @HelloSpeakman yes you are right, I was thinking the same but think if we have operations associated with each one to many relation records then this will go exponential complexity. – BetaDev Feb 19 '18 at 17:16
  • It sounds smart. I will check and let you know. Thanks! – crowley Feb 19 '18 at 17:23
  • Possible duplicate of [Laravel check if related model exists](https://stackoverflow.com/questions/23910553/laravel-check-if-related-model-exists) – Royce Feb 19 '18 at 17:29
  • It works ;), it was so easy... Thanks once again. – crowley Feb 19 '18 at 18:28

0 Answers0