Wednesday, December 29, 2021

[FIXED] laravel 8 update child table data from parent table

Issue

I'm working on a Laravel 8 project.

I have a payments table, it's the migration:

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();
    });

as you can see this table has a foreign key that references on orders table, and it is orders migration:

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();
        });

I created a one to one relationship in Order model:

class Order extends Model
{
    use HasFactory;

    protected $guarded = [];

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

The problem is that when I want to use order() method on Payment class it does not work. for example:

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

I get this error:

BadMethodCallException Call to undefined method App\Models\Payment::order()

UPDATE: Here is Payment model:

class Payment extends Model
{
    use HasFactory;

    protected $guarded = [];
    
}

Thank you for helping me.


Solution

You have to describe the order relation ship in the Payment model

class Payment extends Model
{
    use HasFactory;

    protected $guarded = [];

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

and after that you can access the payment's order like this:

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


Answered By - Mátyás GrÅ‘ger

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.