samedi 13 juillet 2019

Laravel belongsToMany

I have 3 tables:

User
    - id
    - email

UserAccount
    - id
    - user_id
    - account_id

Account
    - id
    - org_name
    - user_id

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 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.

Too few arguments to function Account::App\Models\{closure}(), 1 passed and exactly 2 expected

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);

Account::where('user', function ($q, $user) {
    $q->where('user_id', $user->id);
});

User.php

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

public function userAccount()
{
    return $this->belongsToMany(Account::class, User::class, 'acct_id', 'user_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');
}

Account.php

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

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

Any thoughts?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire