Laravel 4:雄辩的软删除和关系

时间:2013-11-20 17:24:34

标签: laravel-4 eloquent

我有2个表,客户端和项目,并且项目与客户端相关联。客户端和项目都实现软删除以维护存档的原因,即使我删除了客户端,项目仍然会附加客户端信息。

我的问题是,当我删除客户端时,该引用将无法从项目中访问并引发异常。我想做的是软删除客户端,但保留项目关系中的客户端数据。

我的刀片代码如下:

@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');


    });

非常感谢。

2 个答案:

答案 0 :(得分:30)

在定义模型中的关系时,使用withTrashed()方法解决了这个问题。

原始代码:

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

解决方案:

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

非常感谢很高兴帮助。

答案 1 :(得分:3)

在我的情况下,我无法修改Wally提议的功能client,因为它在其他模型和控制器中使用,我不希望它获得客户端{ {1}}。

在这种情况下,我建议采用两种解决方案:

在预先加载客户端时指定->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();
}
相关问题