“Pohon Laravel” Kode Jawaban

Pohon Model Laravel

//Function
public function getTree()
    {
        return AttributeGroupModel::query()->with('attributes')->get()->transform(function ($group) {
            return [
                'id' => $group->id,
                'name' => AdminService::trans($group->name),
                'values' => $group->attributes->map(function ($attribute) use ($group) {
                    return [
                        'id' => $attribute->id,
                        'name' => AdminService::trans($attribute->name),
                        'group_id' => $group->id,
                    ];
                })
            ];
        });
    }

//Model

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Translatable\HasTranslations;

class AttributeGroupModel extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = "attribute_groups";


    protected $fillable = [
        "id",
        "name",
        "sort_order"
    ];

    protected $casts = [
        'name' => 'array',
    ];

    public function attributes()
    {
        return $this->hasMany(AttributeModel::class, 'attribute_group_id', 'id');
    }

}
Shadow

Pohon Laravel

 public function autocomplete(array $tree, $parent_id = 0, $parent_name = null)
    {
        $result = [];
        foreach ($tree as $item) {
            if (!empty($parent_name)) {
                $name = $parent_name . ' > ' . AdminService::trans($item['title']);
            } else {
                $name = AdminService::trans($item['title']);
            }
            $result[] = [
                'id' => $item['id'],
                'title' => $name,
            ];
            if (count($item['children']) > 0) {
                $result = array_merge($result, $this->autocomplete($item['children'], $parent_id, $name));
            }
        }
        return $result;
    }
Shadow

Jawaban yang mirip dengan “Pohon Laravel”

Pertanyaan yang mirip dengan “Pohon Laravel”

Lebih banyak jawaban terkait untuk “Pohon Laravel” di PHP

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya