Answer the question
In order to leave comments, you need to log in
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);
id
name
id_user
execute_id
direction_id
id
name
last_name
id_user
Answer the question
In order to leave comments, you need to log in
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question