2013-11-20 110 views
10

我有2個表,客戶端和項目,並且項目與客戶端相關聯。客戶和項目都實施了軟刪除以維護關係,因爲存檔原因,即使我刪除了客戶,項目仍然會附加客戶信息。Laravel 4:雄辯軟刪除和關係

我的問題是,當我刪除客戶端時,引用變得無法從項目中訪問並引發異常。我想要做的是軟刪除客戶端,但保留項目關係中的客戶端數據。

我的刀片代碼如下:

@if ($projects->count()) 
<table class="table table-striped table-bordered"> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Client</th> 
     </tr> 
    </thead> 

    <tbody> 
     @foreach ($projects as $project) 
      <tr> 
       <td>{{{ $project->name }}}</td> 
       <td>{{{ $project->client->name }}}</td> 
       <td>{{ link_to_route('projects.edit', 'Edit', array($project->id), array('class' => 'btn btn-info')) }}</td> 
       <td> 
        {{ Form::open(array('method' => 'DELETE', 'route' => array('projects.destroy', $project->id))) }} 
         {{ Form::submit('Delete', array('class' => 'btn btn-danger')) }} 
        {{ Form::close() }} 
       </td> 
      </tr> 
     @endforeach 
    </tbody> 
</table> @else There are no projects @endif 

下面是遷移:

 Schema::create('clients', function(Blueprint $table) { 

     // Table engine 
     $table->engine = 'InnoDB'; 

     // Increments 
     $table->increments('id'); 

     // Relationships 

     // Fields 
     $table->string('name'); 

     // Timestamps 
     $table->timestamps(); 

     // Soft deletes 
     $table->softDeletes(); 

    }); 


     Schema::create('projects', function(Blueprint $table) { 

     // Table engine 
     $table->engine = 'InnoDB'; 

     // Increments 
     $table->increments('id'); 

     // Relationships 
     $table->integer ('client_id'); 

     // Fields 
     $table->string('name'); 

     // Timestamps 
     $table->timestamps(); 

     // Soft deletes 
     $table->softDeletes(); 

     // Indexes 
     $table->index('client_id'); 


    }); 

非常感謝。

+1

你試過使用':: withTrashed()'嗎? –

+0

您可以顯示遷移嗎?如何以及你究竟想要刪除什麼? – carousel

+0

我正在嘗試刪除(軟刪除)客戶端,但在查看與客戶端相關的項目時保留客戶端名稱。 – Wally

回答

29

這是通過在定義模型中的關係時使用withTrashed()方法解決的。

原始代碼:

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

解決方案:

public function client() { 
    return $this->belongsTo('Client')->withTrashed(); 
} 

非常感謝樂意幫忙。

+0

也適用於我! – od3n

3

在我的情況,我不能修改函數client作爲沃利提出的,因爲它是被其他模型和控制器,我不希望它得到客戶->withTrashed()內使用。

在這種情況下,這裏是兩種解決方案,我建議:

指定->withTrashed()時預先加載客戶端:

$projects = Project::with(['client' => function($query){ $query->withTrashed(); }])->get(); 

或創建一個新client功能->withTrashed()

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

// The new function 
public function client_with_trash() { 
    return $this->belongsTo('Client')->withTrashed(); 
} 

時預先加載現在:

$projects = Project::with(['client_with_trash'])->get();