PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label soft-delete. Show all posts
Showing posts with label soft-delete. Show all posts

Wednesday, January 26, 2022

[FIXED] How to soft delete related records when soft deleting a parent record in Laravel?

 January 26, 2022     eloquent, laravel, laravel-5, php, soft-delete     No comments   

Issue

I have this invoices table that which has the following structure

id | name | amount | deleted_at
2    iMac   1500   | NULL

and a payments table with the following structure

id | invoice_id | amount | deleted_at
2    2            1000   | NULL

Invoice Model

class Invoice extends Model {

    use SoftDeletes;

}

here's the code to delete the invoice

public function cance(Request $request,$id)
{
    $record = Invoice::findOrFail($id);
    $record->delete();
    return response()->json([
        'success' => 'OK',
    ]);
}

Payments model

class Payment extends Model {

    use SoftDeletes;

}

The softDelete on Invoice table works perfectly but its related records (payments) still exists.How do I delete them using softDelete?


Solution

Eloquent doesn't provide automated deletion of related objects, therefore you'll need to write some code yourself. Luckily, it's pretty simple.

Eloquent models fire different events in different stages of model's life-cycle like creating, created, deleting, deleted etc. - you can read more about it here: http://laravel.com/docs/5.1/eloquent#events. What you need is a listener that will run when deleted event is fired - this listener should then delete all related objects.

You can register model listeners in your model's boot() method. The listener should iterate through all payments for the invoice being deleted and should delete them one by one. Bulk delete won't work here as it would execute SQL query directly bypassing model events.

This will do the trick:

class MyModel extends Model {
  protected static function boot() {
    parent::boot();

    static::deleted(function ($invoice) {
      $invoice->payments()->delete();
    });
  }
}


Answered By - jedrzej.kurylo
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, January 5, 2022

[FIXED] CakePHP 3 - How to still contain() soft-deleted entities?

 January 05, 2022     cakephp, cakephp-3.0, orm, soft-delete     No comments   

Issue

I have an Orders and a Users table, such that Orders belongsTo Users.

I want users to be able to soft-delete their account, so I added a deleted field and modified the delete method. The user info is needed for administrative purposes, hence no hard deletes.

I also overrode the default finder of UsersTable such that deleted users will not pop up in lists or as results of Users->get():

public function findAll(Query $query, array $options)
{
    return $query->where(['Users.deleted' => false]);
}

I am satisfied with the way it works, mostly that I now cannot forget to exclude deleted users as the default finder already does the job.

The problem is I still want to include the user when it is contained from an order:

$order = $this->Orders->get($id, ['contain' => 'Users']);

And apparently when using contain() findAll() is used, because this does not include the deleted user.

How can I still include the soft-deleted entities in a contain()?

Is it possible to set a different default finder for contains?


Solution

You can for example use the finder option for contain to specify which finder to use, like:

$this->Orders->get($id, [
    'contain' => [
        'Users' => [
            'finder' => 'withDeleted'
        ]
    ]
]);

or modify the query directly:

$this->Orders->get($id, [
    'contain' => [
        'Users' => function (\Cake\ORM\Query $query) {
            return $query->find('withDeleted');
        }
    ]
]);

See also Cookbook > Database Access & ORM > Query Builder > Passing Conditions to Contain

However any custom finder would circumvent your modified all finder, which shows a flaw in your approach, once a query uses a different finder, and doesn't also explicitly use the all finder, your conditions will not be applied, which you most likely wouldn't want to happen so easily.

A better approach would probably be to use the Model.beforeFind event/callback. Here's a basic, rather strict example that uses an options approach:

public function beforeFind(\Cake\Event\Event $event, \Cake\ORM\Query $query, \ArrayObject $options)
{
    if (!isset($options['findWithDeleted']) ||
        $options['findWithDeleted'] !== true
    ) {
        $query->where(['Users.deleted' => false]);
    }
}

public function findWithDeleted(\Cake\ORM\Query $query, array $options)
{
    return $query->applyOptions(['findWithDeleted' => true]);
}

This would ensure that only when the findWithDeleted option is present, and set to true, the condition would not be applied.

You might also want to have a look at plugins that can handle this, like for example https://github.com/usemuffin/trash.



Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 2, 2022

[FIXED] Column not found: 1054 Unknown column 'orders.deleted_at' in 'where clause'

 January 02, 2022     eloquent, laravel, laravel-5, soft-delete     No comments   

Issue

In my table i don't have deleted_at column.

But in laravel model in return deleted_at is null in where condition.

Below is my code

public function load($id) {

        return $this
            ->select(sprintf('%s.*', $this->getTable()))
            ->where(sprintf('%s.id', $this->getTable(), $this->getKeyName()), '=', $id)
            ->first();
    }

can someone helps me? How to fix this?


Solution

You have to remove the traits use SoftDeletes; from your model file.

and then use below code:

 return $this->where(sprintf('%s.id', $this->getTable(), $this->getKeyName()), '=', $id)
        ->pluck('id');'


Answered By - Madhuri Patel
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

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
All Comments
Atom
All Comments

Copyright © PHPFixing