简体   繁体   中英

How to insert pivot table in case of many to many relation? (Laravel 5.3)

My form to add data is like this :

在此处输入图片说明

When klik save, It will call controller

My controller is like this :

public function store(Request $request)
{
    $param = $request->only('account_name','account_number','bank_id','branch');
    $result = $this->user_service->addUserBank($param);

    if($result)
        $status='success';
    else
        $status = 'failed';
    return redirect('member/profile/setting/account')->with('status',$status);
}

My service is like this :

public function addUserBank($param)
{
    $instance = User::where('id', '=', auth()->user()->id)->first();
    $param['user_id'] = auth()->user()->id;
    $param['status'] = 0;
    $instance->banks()->attach([
                'status' => $param['status'], 
                'account_name' => $param['account_name'],
                'account_number' => $param['account_number'],
                'branch' => $param['branch']
            ]);
    return $result;
}

My model user is like this :

<?php
namespace App;
use App\Models\MasterData;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable, FormAccessible;
    protected $fillable = [
        'name', 'email', 'password', 'api_token','birth_date','mobile_number','gender','full_name'
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function banks()
    {
        return $this->belongsToMany(MasterData::class, 'users_banks', 'user_id', 'bank_id')  ->withPivot('status','account_name','account_number','branch')->withTimestamps();
    }
}

So I have 3 table : users table, users_banks table (pivot table), and master_datas table

List of the names of the banks located in the master_datas table with type bank

Users table have field id, name, email, password etc => See model user

Master_datas table have field id (this is bank id), name (this is bank name), type (there exist type of bank, order status etc. So, get type = bank)

Users_banks table have field id, user_id, bank_id, status, account_name, account_number, branch

When run, it does not successfully insert into the pivot table (table users_banks).

It looks like my way to insert into the pivot table, not true.

Can you help me?

Additional

Table Master_datas is like this :

在此处输入图片说明

The problem is that you are not passing bank_id in your addUserBank() method. you can do it as:

public function addUserBank($param)
{
    $param['status'] = 0;
    auth()->user()
          ->banks()
          ->attach($param['bank_id'], array_only($param, ['status', 'account_name', 'account_number', 'branch']);
    return true;
}

Note: You don't need to set user_id explicitly here as Laravel will automatically do it for you.

Docs

Create UserBank model:

 <?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class UserBank extends model 
    {
        protected $table = 'user_banks';
        protected $fillable = ['user_id','bank_id'];
    }

And then populate the table from controller:

public function store(Request $request)
{
    $param = $request->only('account_name','account_number','bank_id','branch');
    $result = $this->user_service->addUserBank($param);

    if($result)
    { 
        $pivot=new UserBank();
        $pivot->user_id=auth()->user()->id;
        $pivot->bank_id=$request->bank_id;
        if($pivot->save())
         {
             $status='success';
         }
    }
    else
    {            
            $status = 'failed';
    }

    return redirect('member/profile/setting/account')->with('status',$status);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM