繁体   English   中英

Laravel雄辩:将新模型与相关新模型一起存储

[英]Laravel eloquent: store new model with related new models

我正在尝试存储具有许多相关新模型的新模型。

我有我的服务模式

class Service extends Model{
    public function serviceoperations() {
        return $this->hasMany("App\Models\ServiceOperation");
    }
}

和我的ServiceOperation模型

class ServiceOperation extends Model{
    public function service() {
        return $this->belongsTo("App\Models\Service");
    }
}

在我的商店功能中,我正在使用事务创建具有许多服务操作模型的新服务模型:

use App\Models\Service;
use App\Models\ServiceOperation;
use Illuminate\Support\Facades\DB;

    public function store(Request $request) {
        $service = new Service();
        $ops = [];
        foreach ($operations as $operation) {
            $op = new ServiceOperation();
            $ops[] = $op;
        }
        DB::transaction(function()use($service, $ops) {
            $service->save();
            $service->serviceoperations()->saveMany($ops);
        });
    }

我的问题是:是否有另一种方式我的新的相关serviceoperation模型添加到我的新的服务模式,并在数据库中坚持他们在一个单一的命令?

您必须使用关联方法。

$service->serviceoperations()->associate($serviceoperations)

希望它能对您有所帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM