2017-01-26 3 views
0

두 개의 테이블이 있습니다. 표 reportsLaravel의 피벗 테이블에서 행 삭제

report_id | user_id | item_id 

reports_messages

report_id | user_id | item_id | messages 

내가 reports_messagesreport_id 일치하는 모든 관련 행이 너무 삭제 될 reportsreport_id을 삭제하면 내가 원하는. 내 ReportMessages 모델에서

나는

public function reportedItem(){ 

    return $this->belongsTo('App\Item'); 
} 

public function user(){ 
    return $this->hasOne('App\User', 'id', 'user_id'); 
} 

지금까지 내가 SO

public function destroy($report_id){ 

    Report::destroy($report_id); 
    ReportMessages::find(1)->reports()->where('report_id',$report_id)->delete(); 

    return redirect()->route('user.ports'); 

이 삭제 여기에 설립 된이 솔루션을 시도한 보고서 모델에서이 관계

public function reports(){ 
    return $this->belongsTo('App\Report'); 
} 

public function item(){ 
    return $this->belongsTo('App\Item', 'item_id', 'id'); 
} 

에게 있습니다 reports에서만 ... 피봇 테이블에서 관련 report_id를 삭제하지 않습니다. }

답변

2

Laravel에는 피벗 테이블을 처리 할 수있는 detach and attach 함수가 있습니다. 그래서 당신은 피벗 테이블에서 레코드를 제거하기 위해이 작업을 수행 할 수 있습니다

ReportMessages::find(1)->reports()->detach($report_id); 

이를가 또 다른 객체에 링크 될 수 있기 때문에 그러나 보고서 테이블에 행을 제거하지 않습니다.

업데이트 :
그래서, 난 그냥 발견, 당신은 연결되는 두 개의 모델을 가지고, 피벗 테이블이 없습니다. 당신은 ReportMessages를 제거하려면 쿼리에 reports() 관계를로드 할 필요는 없습니다

, 당신은 다음과 같이 그것을 바로 할 수 있습니다

Report::destroy($report_id); 
ReportMessages::where('report_id',$report_id)->delete(); 

이 보고서를 제거하고 모든 해당 reportmessages 것입니다.

+0

감사합니다. 이 오류가 발생했습니다. '정의되지 않은 메소드 호출 \ Database \ Query \ Builder :: detach()'가 나타납니다. – user5996816

+0

내 대답이 업데이트되었지만 실제로 피벗 테이블이 없습니다 ... – Jerodev

+0

오, 맙소사. 그리고 저는 피봇 테이블을 가지고 그것을하려고했습니다. 그들은 실제로 모델에 의해서만 연결됩니다. 바보 나. 도와 주셔서 감사합니다! – user5996816

관련 문제