K
K
Konstantin Tolmachev2018-04-14 06:15:33
Laravel
Konstantin Tolmachev, 2018-04-14 06:15:33

Database optimization. How to make a relationship query and field formation in one query?

Greetings colleagues, the essence is this, there is a model with relationships that refers to itself

public function getUnitedNameAttribute()
  {
    $additional_name = $this->dependantGroup()->get();
    $name = $this->name;
    return  $name . (($additional_name->count() > 0) ? " / " .$additional_name->first()->name : "");
 	}

    public function dependantGroup()
  {
    return $this->hasOne(Group::class, 'united_with');
  }
 	public function parentGroup()
  {
    return $this->belongsTo(Group::class,'id');
  }

And everything works fine, but the problem is that if we request a group of values, a new request is created for each individual element, which forms the combined name. Question: How can I change (supplement) this code in order to generate the necessary data with one or several requests, but not a hundred. I've been digging around, but so far, frankly, nothing comes to mind.
Maybe there is an opportunity to somehow collect this matter through scopes, but to be honest, I don’t quite understand how.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor, 2018-04-14
@v_decadence

https://laravel.com/docs/5.6/eloquent-relationship...

K
Konstantin B., 2018-04-14
@Kostik_1993

You need to use the with() method if I understood you correctly

$groups = Group::with('dependantGroup', 'parentGroup')->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question