gpt4 book ai didi

laravel-4 - 拉拉维尔 4 : Eloquent soft deletes and relationships

转载 作者:行者123 更新时间:2023-12-02 14:41:43 26 4
gpt4 key购买 nike

我有 2 个表、客户和项目,并且一个项目与客户关联。出于存档原因,客户和项目都实现软删除来维护关系,即即使我删除客户,项目仍会附加客户信息。

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

我的 Blade 代码如下:

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


});

非常感谢。

最佳答案

这是通过在模型中定义关系时使用 withTrashed() 方法解决的。

原始代码:

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

解决方案:

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

非常感谢很高兴提供帮助。

关于laravel-4 - 拉拉维尔 4 : Eloquent soft deletes and relationships,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com