【问题标题】:laravel 8 update child table data from parent tablelaravel 8 从父表更新子表数据
【发布时间】:2022-01-27 04:44:31
【问题描述】:

我正在开发一个 Laravel 8 项目。

我有一个payments 表,这是迁移:

Schema::create('payments', function (Blueprint $table) {
        $table->id();
        $table->enum('gateway',['idpay','zarinpal']);
        $table->unsignedInteger('res_id')->nullable();
        $table->char('ref_code',128)->nullable();
        $table->enum('status',['paid','unpaid']);
        $table->unsignedBigInteger('order_id');
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
        $table->timestamps();
    });

你可以看到这个表有一个外键引用orders表,它是orders迁移:

Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->unsignedInteger('amount');
            $table->char('ref_code',128)->nullable();
            $table->enum('status',['unpaid','paid',]);
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });

我在Order 模型中创建了一对一的关系:

class Order extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function payment()
    {
        return $this->hasOne(Payment::class);
    }
}

问题是,当我想在 Payment 类上使用 order() 方法时,它不起作用。 例如:

Payment::find(10)->order()->update(['status' =>'paid']);

我收到此错误:

BadMethodCallException 调用未定义的方法 App\Models\Payment::order()

更新: 这里是Payment 模型:

class Payment extends Model
{
    use HasFactory;

    protected $guarded = [];
    
}

谢谢你帮助我。

【问题讨论】:

  • App\Models\Payment.phpfunction order() 吗?
  • @Ron 不,因为我的payment_id 表中没有payment_id 列。我的payments 表中有order_id

标签: laravel


【解决方案1】:

您必须在付款模型中描述订单关系

class Payment extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}

然后您可以像这样访问付款订单:

Payment::find(10)->order->update(['status' =>'paid']);

【讨论】:

    【解决方案2】:

    您应该在付款模型中使用这样的方法。

    public function order()
    {
        return $this->belongsTo(Order::class);
    }
    

    因为您在付款模式中仍然没有任何关系来订购。

    您可以在这里查看详细信息。

    https://laravel.com/docs/8.x/eloquent-relationships#one-to-one-defining-the-inverse-of-the-relationship

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2020-06-28
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多