Terms table:

  • term_id

  • name

  • slug

Term_taxonomy table:

  • term_taxonomy_id

  • term_id

  • description

My Term model:

public function TermTaxonomy(){
    return $this->hasOne('TermTaxonomy');
}

My TermTaxonomy model:

public function Term(){
    return $this->belongsTo('Term');
}

I want to delete related data from Terms and Term_taxonomy Table , as I do so far is:

$category = Term::with('TermTaxonomy')->find($id);
// delete related   
$category->TermTaxonomy()->delete();
$category->delete();

It works, but is there any best way method to delete related data and how to use it?

closed as primarily opinion-based by EmilandrewsiAlex KRavi Dhoriya ツuser3473830 Jan 23 '15 at 8:43

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

3 Answers 正确答案 

I recommend you use a foreign key constraint make it so on delete, referencing records will be deleted as well.

With Laravels Schema Builder:

$table->foreign('term_id')
      ->references('term_id')->on('terms')
      ->onDelete('cascade');

Now every time you delete a Term all related TermTaxonomy will be deleted.

In case you don't use the Schema Builder: MySQL reference

I agree that better is to create foreign keys, but if you for some reason don't want to, you can do a small change to your Term model.

at end of class add this:

public function delete(){
   $this->TermTaxonomy()->delete();
   return parent::delete();
}

so laravel will delete taxonomies when you will call Term::find($id)->delete();

You can also try Model Event.

class Term extends Eloquent {
  public static function boot()
  {
    parent::boot();

    // Setup event bindings...
    static::deleting(function($term)
    {
      //delete related  
      if($term->TermTaxonomy()->delete()){
         return true;
      }
      return false;
    });
   }
}

Add boot function in Term Model

When you delete Term record first call deleting method. if deleting method is return true than delete record otherwise not delete.

$category = Term::with('TermTaxonomy')->find($id);
$category->delete();

http://laravel.com/docs/4.2/eloquent#model-events

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


来自  https://stackoverflow.com/questions/28097859/how-to-delete-related-data-one-to-one-relationships-lar...