I am using Laravel 4
with MySQL
back-end.
I have two database tables namely - surveyes
and templates
.
Bo
One possible solution to this problem is to use the Nested Sets model. This avoids the problem of recursive queries. There are two available Laravel packages that extend Eloquent to implement Nested Sets: Laravel-NestedSet and Baum. I understand you have the issue of existing data; however, it shouldn't be too hard to make a one-time migration script. You can create new models using whichever nested sets library you pick; these models will have methods to set the parent node of a survey. You can have the new survey data in a new table (you can override the table name in Eloquent; see here. Then, write a script or protected controller action to migrate the existing surveys to the new table. It will work something like this (using the laravel-nestedset syntax; Baum is similar):
$oldSurveys = Survey::all();
$oldSurveys->each(function($survey) {
$newSurvey = NestedSurvey::create(array($survey->name, $survey->type ...etc));
});
$newSurveys = NestedSurvey::whereNotNull('parent_id');
$newSurveys->each(function($survey) {
$parent = NestedSurvey::find($survey->parent_id);
$survey->appendTo($parent)->save();
});
Once you have imported all your survey into the new table, you can switch your application over to use the new models.
Now, you'll be able to fetch an arbitrarily deep hierarchy in linear time. And since your model extends Eloquent, you can get any related columns just as you normally would.