【问题标题】:inserting data into database laravel 5.6 relation belongstomany pivot table将数据插入数据库 laravel 5.6 关系属于任何数据透视表
【发布时间】:2018-06-25 19:20:03
【问题描述】:

我想知道如何在使用属于多个关系时将数据插入数据透视表我现在可以从数据库中读取数据但我不知道如何将数据存储在数据库和我的 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 或 ids,因为它必须是多个产品并将它们保存到 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();
    });
}

【问题讨论】:

标签: php laravel


【解决方案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();
    });
}

【讨论】:

  • oya 那是我的错误对不起,是的,好吧,我试试看会发生什么:)
  • 我应该在 store 函数中写那个吗??
  • 我的意思是这是我用于存储的控制器,我使用 make 命令我应该在这里做吗? $invoices = Invoice::create([ 'title' => $request->title, 'description' => $request->description, 'client_id' => $request->client_id, ]);
  • 你可以在任何你需要的地方写它@Farshad :)
猜你喜欢
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2014-09-29
  • 1970-01-01
  • 2015-01-10
  • 2020-05-01
相关资源
最近更新 更多