Cómo mostrar todos los valores de padres e hijos en una sola gota selecta en javascript

Hola chicos Tengo tabla de temas donde estoy almacenando todos los temas junto con sub temas..y subtopic id estoy almacenando en la columna parent_id.

Aquí está mi estructura db: enter image description here

Estoy recibiendo todos los temas en desplegamiento como este. Pero me gustaría mostrar mi lista de subtemas así

fractions 
fractions>introductions to fractions
fractions>Fractions as division

Hasta ahora he creado ChildTopics funciones en mi modelo:

public function childTopics()
{
    return $this->hasMany(Topic::class, 'parent_id');
}

Y usé mi función de creación en el controlador así:

 $topics = Topic::with('childTopics')->parent()->get(['id', 'name']);
   

Aquí está mi llamada ajax donde estoy mostrando todos mis temas en un solo lugar.

function getSubjectsTopics(subject_id)
{
    if(subject_id) {
        loading_show();
    axios.get("/master/topic/get-topic-by-subject-id/" + subject_id)
        .then(function(response) {
            var optionHtml = '';
            if(response.data.status) {
                $.each(response.data.subject_topics, function(i,v) {
                    optionHtml += ``;
                 });
            }

            $("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
            loading_hide();
        })
        .catch(function(error) {
            loading_hide();
            console.log(error);
            Swal.fire({
                type: 'error',
                title: 'Oops...',
                text: 'Something went wrong!'
            })
        })
    } else {
        $("#ddl_topic_type").attr('disabled', true);
    }
}

En esta llamada ajax me gustaría mostrar mis subtemas con el nombre de tema padre en sí.

¿Puede alguien ayudarme cómo puedo mostrarlo? Gracias por adelantado.

Editar: Aquí está mi salida de respuesta enter image description here

Aquí están las funciones para conseguir temas basados en tema:

public function getTopicsBySubjectID($subject_id)
{
    $topics = Topic::where("subject_id", $subject_id)->get(['id', 'name']);

    return response()->json(['status' => 'success', 'subject_topics' => $topics], 200);
}

Pregunta hecha hace 3 años, 5 meses, 0 días - Por pixelprodigy50bb


3 Respuestas:

  • Puedes usar optGroup para agrupar su sub opción en un grupo donde optGroup tendrá el nombre del subject name .Tu corriente ajax response Mostrar todo subject_topics así que si el primer valor fractions es el nombre de sujeto que puede poner la condición dentro each bucle para comprobar si i(posición) 0 después del apéndice optgroup.

    Código de Demo :

    var response = {
      'data': {
        'status': 'success',
        'subject_topics': [{
          'id': 0,
          'name': 'fractions'
        }, {
          'id': 1,
          'name': 'fractions of booksss of subject'
        }, {
          'id': 2,
          'name': 'fractions of sub'
        }]
    
      }
    };
    var optionHtml = '';
    if (response.data.status) {
      $.each(response.data.subject_topics, function(i, v) {
        if (i == 0) {
          optionHtml += `` //considering 1st id is subject name
        } else {
          optionHtml += ``;
        }
      });
      optionHtml += `` //close optgroup
    }
    
    $("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
    
    //or
    var response = {
      'data': {
        'status': 'success',
        'subject': 'somesubjectname', //return subject name as well
        'subject_topics': [{
          'id': 0,
          'name': 'fractions'
        }, {
          'id': 1,
          'name': 'fractions of booksss of subject'
        }, {
          'id': 2,
          'name': 'fractions of sub'
        }]
    
      }
    };
    var optionHtml1 = '';
    
    if (response.data.status) {
      //append subject name
      optionHtml1 += ``
      $.each(response.data.subject_topics, function(i, v) {
        optionHtml1 += ``;
      });
      //subject name ..
      optionHtml1 += ``
    }
    
    $("#ddl_topic_type1").html(optionHtml1).attr('disabled', false).select2();
    
    
    
    
    

    Respondida el Dec 17, 2020 a las 06:08 - por quantumcoder403a

    Votos positivos: 0 | Votos negativos: 0

  • Para lograr mostrar los subtemas con el nombre del tema padre en la gota selecta con JavaScript, puedes modificar tu función getSubjectsTopics de la siguiente manera:

    ``javascript function getSubjectsTopics(subject_id) { if (subject_id) { loading_show(); axios.get("/master/topic/get-topic-by-subject-id/" + subject_id) .then(function (response) { var optionHtml = '<option value="0">Parent</option>'; if (response.data.status) { $.each(response.data.subject_topics, function (i, v) { var topicName = v.name; if (v.parent) { topicName = v.parent.name + " > " + v.name; } optionHtml +=`; }); }

                $("<h51>ddl_topic_type").html(optionHtml).attr('disabled', false).select2();</h51>                loading_hide();
            })
            .catch(function (error) {
                loading_hide();
                console.log(error);
                Swal.fire({
                    type: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong!'
                })
            })
    } else {
        $("<h34>ddl_topic_type").attr('disabled', true);</h34>    }
    

    } ```

    En esta modificación, hemos agregado una condición para verificar si el subtema tiene un tema padre. Si tiene un tema padre, concatenamos el nombre del tema padre con el nombre del subtema separado por un " > ". De esta forma, en el dropdown se mostrará el nombre del tema padre seguido del nombre del subtema.

    Espero que esta solución te sea de ayuda. Si necesitas más asistencia, no dudes en preguntar.

    Respondida el Dec 18, 2020 a las 06:10 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Para mostrar los subtemas con el nombre del tema padre en el elemento desplegable, puedes utilizar una función recursiva en tu archivo JavaScript. Aquí tienes un ejemplo de cómo puedes hacerlo:

    ```javascript function getNestedTopics(topics, parentId) { let options = '';

    for (let topic of topics) { if (topic.parent_id === parentId) { options += <option value="${topic.id}">${topic.name}</option>; options += getNestedTopics(topics, topic.id); } }

    return options; }

    // Obtener todos los temas axios.get("/master/topic/get-topic-by-subject-id/" + subject_id) .then(function(response) { if (response.data.status) { // Crear la opción "Padre" var optionHtml = '';

      // Obtener los temas raíz (sin padre)
      let rootTopics = response.data.subject_topics.filter(topic => topic.parent_id === null);
    
      // Obtener los subtemas para cada tema raíz
      for (let topic of rootTopics) {
        optionHtml += `<option value="${topic.id}">${topic.name}</option>`;
        optionHtml += getNestedTopics(response.data.subject_topics, topic.id);
      }
    
      // Establecer el contenido del elemento desplegable
      $("<h51>ddl_topic_type").html(optionHtml).attr('disabled', false).select2();</h51>    }
    
    loading_hide();
    

    }) .catch(function(error) { loading_hide(); console.log(error); Swal.fire({ type: 'error', title: 'Oops...', text: 'Something went wrong!' }) }); ```

    Esta función recursiva (getNestedTopics) itera sobre la lista de temas y para cada tema, si su parent_id coincide con el parentId proporcionado, agrega una opción al elemento desplegable. Luego, llama recursivamente a sí misma con el id de ese tema como parentId para obtener los subtemas de ese tema.

    De esta manera, puedes crear una lista jerárquica de temas en el elemento desplegable, donde los subtemas se muestran como elementos anidados bajo sus temas padre correspondientes.

    Respondida el Dec 18, 2020 a las 06:13 - por Gemini

    Votos positivos: 0 | Votos negativos: 0