Как построить иерархию папок с laravel? - PullRequest
0 голосов
/ 30 сентября 2019

Это моя модель:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Folder extends Model
{
protected $with = ['children'];

public function children()
{
    return $this->hasMany('App\Models\Folder','parent_id')/*->select('title','path','size','ext','isFolder')*/;
}

public function user()
{
    return $this->belongsTo('App\User','user_id');
}

public static function tree() {

    return static::with(implode('.', array_fill(0, 4, 'children')))->where('parent_id', '=', NULL)->get();

}
}

, и я отображаю результаты с помощью этой функции:

 $folders = Folder::tree();

Я пытаюсь отобразить каждую папку и ее содержимое, независимо от того,файл или другой каталог, есть ли способ сделать это без необходимости делать цикл foreach для каждого уровня?

1 Ответ

0 голосов
/ 30 сентября 2019

Это можно сделать с помощью локальных областей . Если вы также знакомы с recursion , код, который я собираюсь написать, будет легко понять. Все объясняется с комментариями.

/**
 * Retrieve recursively the related children building a tree.
 * Pay attention! this scope may cause A LOT of performance problems. Expecially when there are a lot of children / nephews
 * 
 * @param  Buider  $query
 * @param  integer  $deep  
 * @param  integer $index
 * @return Builder
 */
public function scopeTree($query, $deep, $index = 0) {
  // Increment index
  $index++;

  // Current model is root, let's find the id for base case.
  $id = $this->getKey();

  // Now build the recursive nested query
  return $query->whereHas('children', function($query) use ($deep, $index, $id) {
    // If deep is lower than index, it means we have to add a node to the tree
    if($deep < $index) {
      // Recursion
      $query->tree($deep, $index);
    } else {
      // Base case
      $query->where('parent_id', '=', $id);
    }
  });
}

В любом случае, эта функция может вызвать ОЧЕНЬ много проблем с производительностью, поэтому лучше не углубляться в нее, если в базе данных много записей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...