wim91's avatar

What is the best way to retrieve data from related tables?

Hello everyone. I have three tables that are related. In the handlers, given the record ID of the first table, I need to get an array of values ​​from the third table with certain parameters. Can you tell me the best way to do this? I did it this way, but maybe it's not quite right and there's a better way.

// model 1 table 
public function relation_1()
  {
    return $this->hasMany(TwoTable::class, 'two_id', 'id')
    ->with(['relation_2' => function ($query) {
        $query->select('id', 'three_id')->where('status', 1);
    }]);
  }
// controller
...
	$result = OneTable::with('relation_1')->find($id);
    $collect_res = [];
      if($result){
        foreach ($result->relation_1 as $val) {
          foreach ($val->relation_2 as $val_2) {
            $collect_res[] = $val_2->id;
          }
        }
      }
dd($collect_res);
0 likes
5 replies
wim91's avatar

Thanks for the advice, I'll definitely check out the package. Doesn't it come with built-in mechanisms right out of the box for Laravel?

Glukinho's avatar

Not in all cases. For example, native Eloquent can't handle BelongsToMany relation through multiple models with pivot tables involved.

Imagine you have models: countries, people, companies, and neccessary pivot tables between them. A person can have several citizenships:

  • person -> belongsToMany -> country
  • vice versa, country -> belongsToMany -> person

A person can work in several companies:

  • person -> belongsToMany -> company
  • and vice versa

So, you want to know which countries are represented in a given company. In other words, people of which countries are employed in a company. There is no way to do it using regular Eloquent (at least I haven't found it) while the package I mentioned can do that with ease.

wim91's avatar

Yes, I'm trying to do that. For example, in this example, I only needed the IDs from the third table that matched the condition. I can hide some fields during the query directly in the model, but I'd like to know if there's a way to extract the required array directly, or if I have to assemble it manually?

Please or to participate in this conversation.