Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Ok. So this was a problem caused by a function of how Laravel works.

After some trial and error, I made a guess that Laravel only checks for id's when using pivot magic methods and does not search for any other data.

So I wrote a function to get the preferences, explode them out into the original tags, then compare that tag against the preference list, get the id associated with that tag and then print it to the pivot table with the other data. For testing and double checking purposes the original tag was initially included, then removed later.

    public function move() {
            //get the preferences from the users table (this is stored badly "1-7,3-4,4-6,6-6,6-10,8-5,8-9,8-10,8-13,9-3,9-9") this returns a collection
            $prefs = DB::table('users')->select('id', 'Preferences')->where('Preferences', '!=', '')->get();
                //iterate through each item in the collection
                foreach ($prefs as $pref) {
                     //get the tags only
                     $tags = $pref->Preferences;
                     //break up the tags into a searchable array by exploding each preference at the comma
                     $tag = explode(',', $tags);
                     //for each tag in the array assign it to t
                     foreach ($tag as $t) {
                         //get the id from the preference table when the tag matches t
                         $new = DB::table('prefs')->select('id')->where('tag', $t)->first();
                         //make a new model instance to insert data
                         $taguser = new Tag(array(
                                           'user_id' => $pref->id,
                                           'tag_id' => $t,
                                           'tags' => $new->id
                                          ));
                         //insert data
                         $taguser->save(); 
                         //dd($taguser); <- Since we have a lot of items, dd will break the printout after the first, meaning you can check to see if your information is being handled properly
                     }
                 }
                 return view('refactor');

getting rid of the original tag-id and replacing it with just the plain id that referenced the tag meant that laravel could now search against the correct data and return useful results.

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Mugluck mugluck Joined 19 Oct 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.