mardi 29 août 2017

How to remove a many-to-many relationship based on the Pivot Table information

I am in need to detach records from my pivot table, based on info stored in it.

So I have three tables, 1) Activity 2) activity_submissions 3) Submissions

One activity can have many submissions and one submission can have many activities, they share a many to many relationship. Now there is a catch: the activity_submissions table has a description column in it too.

This is the activity_submissions table:

id | activity_id | submission_id | desription

So I have three records as below:

1 | 20 | 1 | "First"
2 | 20 | 1 | "Second"
3 | 20 | 1 | "Third"

I only want to reove the one with description "Third".

I tried using detach, but that removes all of them:

$activity=\App\Activity::find(20);
$submissions=$activity->submissions()->where('submission_id','=','1')->get();
for($i=0; $i<$submissions->count(); $i++){
    if ($submissions[$i]->pivot->description == "Third"){
       $submissions[$i]->activities()->detach();
    }
}

But this code detaches all my records, how would I go about doing this? I am using Laravel 5.0.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire