R
R
Ruslan Absalyamov2018-03-19 09:40:01
Laravel
Ruslan Absalyamov, 2018-03-19 09:40:01

How to shorten the selection code from the intermediate table?

Which result I want to get looks like this, but I don’t know how to write it in laravel in short.

$id_direction = [];
        //Получаем id direction c условие что вывести все значение у авторизованного пользователя
        $directions = Direction::where('id_user', Auth::user()->id)->get();
        foreach ($directions as $value){
            // Сравниваем id который получили из моделе direction с промежуточной таблицы Execute_direction
            $directionExecute = Exectue_direction::where('direction_id', $value->id)->get();
            foreach ($directionExecute as $item){
                //Получаем всех execute c который id direction должен совпадать
                $executes = Execute::where('id', $item->execute_id)->get();
                foreach ($executes as $key => $execute){
                    // Выходит многомерный массив из следующий данных id_direction -> id_execute и вписываем id name и last name в массив
                    $id_direction[$value->id]['name'] = $value->name;
                $id_direction[$value->id]['execute'][$item->execute_id]['id'] = $execute->id;
                $id_direction[$value->id]['execute'][$item->execute_id]['name'] = $execute->name;
                $arr[$value->id]['execute'][$item->execute_id]['last_name'] = $execute->last_name;
                }
            }

        }

        dd($id_direction);

Only it is difficult for me to implement this code refactoring because I don’t understand how to use it and what should be applied approximately in this model, the table I have is the following
direction
id
name
id_user

execute_direction
execute_id
direction_id

execute
id
name
last_name
id_user

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Absalyamov, 2018-03-24
@rusline18

class Direction extends Model
{
    protected $table = 'direction';
    protected $fillable = ['id_user', 'name'];

    public function executes()
    {
        return $this->belongsToMany('Growth\Execute', 'execute_direction');
    }
}

$arr = [];
        $directions = Direction::where('id_user', Auth::user()->id)->get();
        foreach ($directions as $value){
            $execute = Direction::find($value->id)->executes()->get();
            foreach ($execute as $key => $item){
                $arr[$value->id]['name'] = $value->name;
                $arr[$value->id]['execute'][$item->id]['name'] = $item->name;
                $arr[$value->id]['execute'][$item->id]['last_name'] = $item->name;

            }
        }

N
Nicholas, 2018-03-19
@iNickolay

There is nowhere easier, set up relationships and you will have a code in one line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question