0

I am migrating some entries into Craft for the first time and my saveUp is quite simple where I use the saveElement function. The problem is after doing a few safeUp's and safeDown's I'm getting some appended numbers on my slugs e.g. 'title-07' when ideally it would just stay as 'title'. The slug is based on the title and it appears my safeDown method doesn't hunt down the old slugs wherever they are.

My safeUp() looks something like this:

/*
 * Set the entry and save it
 */

$entry = new Entry();

// Set the entry data
$entry->sectionId   = '4';
$entry->typeId      = '4';
$entry->authorId    = '1';
       
// Title etc..
$entry->title = $title;

// Run saveElement with data
$success = Craft::$app->elements->saveElement($entry);

My safeDown is a bit less elegant:

/*
 * Find the matching entries to delete
 */

$entry = (new \craft\db\Query())
->select("id")
->from("content")
->where( "title = " . $title )
->all();

/*
 * Loop through matches and delete
 */

foreach( $entry as $key => $value ) {

    $rowsAffected = (new \craft\helpers\Db())
    ->delete('content', 'id=' . $value['id'] );
               
}

My question is a couple things.

Is there something as nice as saveElement where I can just pass a typeId and id for the content and everything related gets removed?

My current method where I use craft\helpers\Db->delete leaves behind the original slug. If there's not a cleaner method like saveElement, where can I find the slugs to get rid of them as well?

Any pointers greatly appreciated.

2
  • 1
    Did you try Craft::$app->elements->deleteElement($entry); (docs) orCraft::$app->elements->deleteElementById($entry->id); (docs)? As far as I know, this should cascade delete everything for you. – Oli Mar 30 at 13:39
  • I most certainly did not! Thank you greatly – Robert Mar 30 at 18:22
0

As mentioned by Oli, I was able to use deleteElementById($entry->id). Note $id now refers to $elementId

/*
 * Find the matching entries to delete
 */

$entry = (new \craft\db\Query())
->select("elementId")
->from("content")
->where( "title = " . $title )
->all();

/*
 * Delete the entry
 */
foreach( $entry as $key => $value ) {

  // Hard delete.
  $success = Craft::$app->elements->deleteElementById( $value['elementId'], null, null , true );

}

Now entries deleted also deleted slugs that were created. But there was one problem: entries deleted previously before this migration code upgrade were still there. I found that these slugs were kept in the table element_sites and I manually deleted all the old slugs no longer being used. So far there has been no issue with this and the rest of the site functions apparently normally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.