简体   繁体   English

在多对多关系的情况下如何插入数据透视表? (Laravel 5.3)

[英]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 当klik保存时,它将调用控制器

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 所以我有3个表:users表,users_banks表(数据透视表)和master_datas表

List of the names of the banks located in the master_datas table with type bank 位于master_datas表中类型为bank的存储库的名称列表

Users table have field id, name, email, password etc => See model user 用户表具有字段ID,名称,电子邮件,密码等=>参见模型用户

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) Master_datas表具有字段ID(这是银行ID),名称(这是银行名称),类型(存在银行的类型,订单状态等。因此,获得type = bank)

Users_banks table have field id, user_id, bank_id, status, account_name, account_number, branch Users_banks表具有字段id,user_id,bank_id,状态,account_name,account_number,分支

When run, it does not successfully insert into the pivot table (table users_banks). 运行时,它不会成功插入数据透视表(表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 : 表Master_datas是这样的:

在此处输入图片说明

The problem is that you are not passing bank_id in your addUserBank() method. 问题是您没有在addUserBank()方法中传递bank_id 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. 注意:您不需要在此处显式设置user_id ,因为Laravel会自动为您设置。

Docs 文件

Create UserBank model: 创建UserBank模型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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