使用laravel更新多个表

时间:2018-05-10 17:59:30

标签: php laravel-5 eloquent

我必须在一个请求中更新多个表...为此我创建了一个方法,我写道:

$sector = Sector::where('sectors.id', '=', $id)
    ->join('valuechains', 'sectors.id', '=', 'valuechains.sector_id')
    ->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
    ->join('segments', 'valuechains.id','=', 'segments.valuechain_id')
    ->join('lang_segment', 'segments.id', '=', 'lang_segment.segment_id')
    ->join('keyneeds', 'segments.id', '=', 'keyneeds.segment_id')
    ->join('keyneed_lang', 'keyneeds.id', '=', 'keyneed_lang.keyneed_id');
 $sector->update(
    ['sectors.deleted_at' =>  Carbon::now()],
    ['lang_sector.deleted_at'  => Carbon::now()],
    ['valuechains.deleted_at' => Carbon::now()],
    ['lang_valuechain.deleted_at' => Carbon::now()],
    ['segments.deleted_at' => Carbon::now()],
    ['lang_segment.deleted_at' => Carbon::now()],
    ['keyneeds.deleted_at' => Carbon::now()],
    ['keyneed_lang.deleted_at' => Carbon::now()]
);

不幸的是,我收到了有关'updated_at'的错误消息:

SQLSTATE [23000]:完整性约束违规:1052冠军:'updated_at'dans字段列表est ambigu(SQL {更新sectors内部加入valuechains sectors。{{1} } idvaluechains内部加入sector_id位于lang_valuechainvaluechains = idlang_valuechain内部加入{{1} } valuechain_idsegments = valuechainsid内部加入segments valuechain_idlang_segment = segmentsid上的lang_segment内部加入segment_idkeyneeds = segmentsid内部加入keyneeds segment_idkeyneed_lang = keyneedsid设置keyneed_langkeyneed_id = 2018-05-10 17:54:51,sectors = 2018- 05-10 17:54:51其中deleted_atupdated_at = 2且sectorsid为空)

1 个答案:

答案 0 :(得分:0)

看起来您正在尝试进行级联软删除。您可能希望使用程序包进行调查以帮助简化此操作,您可以查看程序包以实现此here。以下是文档中的一些示例代码:

<?php

namespace App;

use App\Comment;
use Iatstuti\Database\Support\CascadeSoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $cascadeDeletes = ['comments'];

    protected $dates = ['deleted_at'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

或者我建议这样做是一个原始查询,因为我不认为QueryBuilder适合这种情况。