Link to home
Start Free TrialLog in
Avatar of B O
B O

asked on

How do I load the user_id and the sensitivedata_id, in my pivor table, I thaught I had set up every thing accordingly but I have issue with setting up the foreign key I think

I want to set up a many to many relationship between databases in laravel.

I created a two models where by the pivot table suppose to get the id from.
But when I load data to the database the pivot table stays empty.

Here is my code: migration file
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sensitivedata_user', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id');
            $table->integer('creditcard_id');


            $table->timestamps();
        });
    }

Open in new window



Avatar of B O
B O

ASKER

Getting error trying to use foreignid and constrainted method

and migrate it to the database

User generated image
Avatar of Chris Stanyon
Hey there,

I can't quite read your screen shot, but from your migrations list, it looks like you're trying to setup the foreign keys before you've created the CreditCard table - that mirgation is set to run AFTER your pivot table migration (they run in date order), so it can't create the index. Just rename either of those 2 migrations to change the order they run (just change the time part of it:

2021_06_08_200649_create_users ...

Just change that bit to be later that 201625 and then re-run your migrations
Avatar of B O

ASKER

Thank you it worked,

but When i load data my pivot table stays empty
The pivot table will get populated when you attach Relationships (assuming you've set those up correctly), for example:


$user->credit_cards()->attach($creditCardId);

or

$credit_card->users()->attach($userId);
Avatar of B O

ASKER

Thank you for replying

I tried it liek this

Route:
if(!$contact->creditcards()->attach($sensitive_data->id) && !$sensitive_data->users()->attach($contact->id) && !$contact->save() && !$sensitive_data->save())
                {
                    printf('Upload failed');
                } else {
                    printf('Upload success');
                }

Open in new window


When I upload json data to my database
Both  Users and Sensitive tables are filled with data

Except for my sensitivedata_users table, is still empty

User model:
    public function sensitiveData(){


        return $this->belongsToMany('App\Models\SensitiveData');


    }

Open in new window


SensitiveData model:
public function users(){


        return $this->belongsToMany('App\Models\User');


    }

Open in new window







ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial