【问题标题】:Laravel eloquent: store new model with related new modelsLaravel 雄辩:用相关的新模型存储新模型
【发布时间】:2017-09-23 15:27:58
【问题描述】:

我正在尝试存储一个新模型,其中包含许多相关的新模型。

我有我的服务模型

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");
    }
}

在我的 store 函数中,我正在使用 transaction 创建一个具有许多服务操作模型的新服务模型:

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 模型中,并将它们保存在单个命令中的数据库?

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-eloquent


    【解决方案1】:

    你必须使用associate方法。

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

    希望对你有帮助:)

    【讨论】:

    • 我不确定它是否有效。看着this question,我应该先保存我的服务模型,然后才能打电话给同事。无论如何,我只是尝试过,它不起作用。我也尝试了反向$operation->service()->associate($service),但它并没有保存创建的新操作。
    猜你喜欢
    • 2013-07-30
    • 2014-08-03
    • 1970-01-01
    • 2021-08-11
    • 2019-02-12
    • 1970-01-01
    • 2013-06-04
    • 2016-11-26
    • 2018-02-19
    相关资源
    最近更新 更多