【问题标题】:Eloquent How do I store data if i have 2 models with "one-to-many" on one model?Eloquent 如果我在一个模型上有 2 个“一对多”模型,我该如何存储数据?
【发布时间】:2018-10-29 10:01:51
【问题描述】:

好的,我有以下 ER 图,显示了我在 DB 中的关系: 我愿意在生成Order 时生成UserOrder 可以包含许多ProductsOrders 也按其transaction_id 分组,因此我可以将所有产品包含在同一用户的同一顺序中。我正在尝试将它们全部保存,但我得到了Field 'transaction_id' doesn't have a default value。我设法保存了用户,也将订单与产品和用户联系起来,但我仍然不知道如何保存与订单相关联的 transaction_id。 这些是我的迁移:

Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->integer('transaction_id')->unsigned();
            $table->foreign('transaction_id')->references('id')->on('transactions');
            $table->timestamps();

Schema::create('order_product', function (Blueprint $table) {
            $table->integer('order_id')->unsigned()->index();
            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            $table->integer('product_id')->unsigned()->index();
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->integer('quantity')->unsigned();
            $table->timestamps();
        });
Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->float('price',8,2);
            $table->timestamps();
        });
Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id');
            $table->enum('status',['open','closed']);
            $table->timestamps();
        });

我的模型:

用户模型:

public function orders() {return $this->hasMany(Order::class);}

订购型号:

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

    public function products()
    {
        return $this->belongsToMany(Product::class)
        ->withPivot('quantity')
        ->withTimestamps();
    }

    public function transaction()
    {
        return $this->belongsTo(Transaction::class);
    }

交易模型:

public function orders() {return $this->hasMany(Order::class);}

这就是我试图保存它们的方式:

$user->save();
$transaction->save();
$order = new Order();
$order->user_id = $user->id;
$user->orders()->save($order);
$transaction->orders()->save($order);
$order->products()->attach($cartItem->id, ['quantity' => $cartItem->qty]);

附:抱歉,帖子太长了,我没有主意。

【问题讨论】:

    标签: php laravel-5 database-design eloquent relational-database


    【解决方案1】:

    使用这个:

    $order = new Order();
    $order->user_id = $user->id;
    $order->transaction_id = $transaction->id;
    $order->save();
    

    【讨论】:

    • 这太简单了!不敢相信我错过了这一部分。谢谢!
    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多