将数据插入数据库laravel 5.6关系属于所有数据透视表

时间:2018-06-25 11:06:53

标签: php laravel

我想知道如何在使用一个多属关系时将数据插入数据透视表中,我现在可以从数据库中读取数据,但是我不知道如何将数据存储在数据库中,在我的invoice_product表中,代码是 激励模式:

   class Invoice extends Model
{
    protected $fillable = ['title','description','client_id','product_id'];
    public function user() {
        return $this->hasOne('App\Client','id','client_id');
    }
    public function products()
    {
        return $this->belongsToMany('App\Product', 'invoice_product', 'invoice_id')
            ->withPivot('product_quantity')
            ->as('invoice_products_pivot');

    }
}

发票控制人:

public function store(Request $request)
{
    //Validate
    $request->validate([
        'title' => 'required|min:3',
        'description' => 'required',
    ]);

    $invoices = Invoice::create([
        'title' => $request->title,
        'description' => $request->description,
        'client_id' => $request->client_id,
        'product_id' => $request->product_id,

    ]);
    return redirect('admin/invoices/' . $invoices->id);
}

这会将发票存储到发票表中,但是我想获取client_id和product_id或ID,因为它必须是多个产品,并将它们保存到在此处进行迁移的invoice_product表中

 public function up()
{
    Schema::create('invoice_product', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('client_id');
        $table->integer('product_id');
        $table->integer('product_quantity');
        $table->timestamps();
    });
}

1 个答案:

答案 0 :(得分:1)

将数据插入中间表或数据透视表以进行多对多关系 您可以使用如下的附加雄辩方法

$invoice->products()->attach($product_id)
$product->invoices()->attach($invoice_id)

但是您的发票产品迁移看起来有点奇怪

    public function up()
{
    Schema::create('invoice_product', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('invoice_id'); // id of the invoice table
        $table->integer('product_id'); // id of the product table
        $table->integer('product_quantity'); // client_id should go to the invoice table
        $table->timestamps();
    });
}