PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, December 29, 2021

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

 December 29, 2021     laravel     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing