Laravel eloquent insert data with multiple relationship

那年仲夏 提交于 2020-03-05 04:14:09

问题


I have 3 tables:

User
    - id
    - email

UserAccount
    - id
    - user_id
    - account_id

Account
    - id
    - user_id

Verification
    - id
    - user_id
    - guid

I am trying to achieve a post whenever I try to add a user, it will automatically add an account with empty fields but with user_id in it, Verification table with user_id also, at the same time once the Account has been created it should also record UserAccount user_id and account_id but I ended up this error using many to many relationship belongsToMany and sync. How do I add the acct_id and user_id with eloquent?

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acct_id' cannot be null (SQL: insert into `user_accounts` (`acct_id`, `user_id`) values (?, 17))

This is what I've tried so far.

Controller.php

$user = new User();
$user->name = "Not set";
$user->email = $email;
$user->password = NULL;
$user->save();

$accounts = new Account();
$accounts->email = $email;
$user->account()->save($accounts);

$userAccount = new UserAccount();
$userAccount->userAccount()->sync([
   $user->id,
   $accounts->id
]);

User.php

public function account()
{
    return $this->hasMany(Account::class);
}

public function userAccount()
{
    return $this->belongsToMany(User::class, UserAccount::class, 'user_id', 'id');
}

UserACcount.php

public function user()
{
    return $this->hasMany(User::class, 'user_id', 'id');
}

public function account()
{
    return $this->hasMany(Account::class, 'acct_id', 'id');
}

public function userAccount()
{
    return $this->belongsToMany(Account::class, UserAccount::class, 'acct_id', 'user_id');
}

Verification.php

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

Account.php

public function user()
{
    return $this->hasMany(User::class);
}

public function userAccount()
{
    return $this->belongsTo(UserAccount::class);
}

I tried using this functionality and completely works fine but pretty sure this is how it works with eloquent.

$userAcct = new UserAccount();
$userAcct->create([
    'user_id' => $user->id,
    'acct_id' => $accounts->id
]);

Any thoughts?

I also have did found this related problem (Laravel hasManyThrough)


回答1:


First of all, you should remove user_id from the account table because it is already referenced by user_account which links both tables. Moreover, if you wanna take advantages of Eloquent conventions which allow it to guess table names and fields, you should make sure your tables are named users, accounts, verifications and account_user.

User.php

public function accounts()
{
    return $this->belongsToMany(Account::class);
}

Account.php

public function users()
{
    return $this->belongsToMany(User::class);
}

The UserAccount model is useless if account_user exists only to links 2 tables.

Then, you may use an observer to get an event-based approach: whenever an user is created => do something

https://laravel.com/docs/5.8/eloquent#observers

<?php

namespace App\Observers;

use App\Account;
use App\Verification;

class UserObserver
{
    /**
     * Handle the User "created" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        (new Verification)->user()->associate($user);
        $account = new Account;
        $account->save();
        $user->accounts()->attach([
            $account->id
        ]);
    }
}



回答2:


// Post Model
 public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }
    public function tags()
    {
        return $this->belongsToMany('App\Tag')->withTimestamps();
    }

//User Model
 public function posts()
    {
        return $this->hasMany('App\Post');
    }

//Category Model

 public function posts()
    {
        return $this->belongsToMany('App\Post')->withTimestamps();
    }

//Tag Model 

public function posts()
    {
        return $this->belongsToMany('App\Post')->withTimestamps();
    }


来源:https://stackoverflow.com/questions/57031129/laravel-eloquent-insert-data-with-multiple-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!