【发布时间】: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.php有function order()吗? -
@Ron 不,因为我的
payment_id表中没有payment_id列。我的payments表中有order_id。
标签: laravel