Laravel 4: Eloquent软删除和关联

12

我有两个表,客户和项目,一个项目与一个客户相关联。为了归档目的,客户和项目都实现了软删除以维护关系,即使我删除了一个客户,项目仍将附有客户信息。

我的问题是,当我删除客户时,引用从项目中变得无法访问并抛出异常。我想做的是对客户进行软删除,但保留来自项目关系的客户数据。

我的刀片代码如下:

@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()吗? - Glad To Help
你能展示迁移吗?你想要删除什么,以及具体怎么做? - Miroslav Trninic
我正在尝试删除(软删除)客户,但在查看与客户相关的项目时保留客户名称。 - Qubical
关于上述代码,我该如何实现 withTrashed? - Qubical
请忽略上面的内容,模型中的 withTrashed() 似乎是答案。所以... public function client() { return $this->belongsTo('Client')->withTrashed(); } - Qubical
2个回答

32

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

原始代码:

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

解决方法:

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

非常感谢 Glad to Help。


3
在我的情况下,我不能像Wally建议的那样修改client函数,因为它被其他我不想获取已删除客户端的模型和控制器使用。
在这种情况下,我提出两种解决方案:
当急切加载客户端时,请指定->withTrashed()
$projects = Project::with(['client' => function($query){ $query->withTrashed(); }])->get();

Or create a new client functions ->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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接