2013-11-20 105 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();