问题
I am using LARAVEL 7 with MySQL back-end.
I have a topics table with columns id, name, and parent. Here, parent is foreign-key of the column Id. The data in table is as below :
i am trying to show those topics names like this
fractions
- fractions > introduction to fractions
- fractions > introduction to fractions > What are fractions and its purpose?
- fractions > introduction to fractions > Fractions as division
- fractions > Representation of fractions
- fractions > Representation of fractions > How to represent a fraction - Area Models
here is my ajax call where i am showing all topics :
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) {
optionHtml += `<option value="${v.id}">${v.name}</option>`;
});
}
$("#ddl_topic_type").html(optionHtml).attr('disabled', false).select2();
loading_hide();
//console.log(response);
})
.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);
}
}
here is the function from controller where i am getting all topics:
public function getTopicsBySubjectID($subject_id)
{
$topics = Topic::where("subject_id", $subject_id)->get(['id', 'name']);
$sub_topics = Topic::with('childTopics')->parent()->get(['id', 'name']);
return response()->json(['status' => 'success', 'subject_topics' => $topics, 'sub_topics' => $sub_topics], 200);
}
here is my model function where i am getting only topics with one level only:
public function parentTopic()
{
return $this->belongsTo('App\Models\Topic', 'parent_id');
}
public function scopeParent($query)
{
return $query->whereNull('parent_id');
}
Now in my topic dropdown i am getting topics like this : [![enter image description here][2]][2]
Can anyone help me how can i change the hierarchy..thanks in advance. [2]: https://i.stack.imgur.com/7XN5Z.png
来源:https://stackoverflow.com/questions/65352399/how-to-make-tree-structure-heirarachy-for-select-dropdown-in-laravel-ajax