2013-11-20 16 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'); 
} 

ソリューション:Helpへグラッドへ

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

感謝します。

+0

も私のために働きます! – od3n

3

私の場合、Wally提案のようにclientという機能を変更することはできません。他のモデルやコントローラで使用されていて、クライアントを取得したくないからです。->withTrashed()この場合

は、ここで私が提案する2つの解決策は次のとおりです。

$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(); 
} 

熱心なロードを作成します。

->withTrashed()ときイーガーローディングクライアントを指定します現在:

$projects = Project::with(['client_with_trash'])->get(); 
関連する問題