在 Laravel 4 中保存一对一的多态关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23273817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:24:59  来源:igfitidea点击:

Saving a One to One Polymorphic relation in Laravel 4

phplaravellaravel-4eloquent

提问by Joaquín L. Robles

I'm having some trouble while saving a polymorphic one-to-one relation with Laravel 4, this is my model:

我在保存与 Laravel 4 的多态一对一关系时遇到了一些麻烦,这是我的模型:

namespace App\Models\Proveedores;

class Proveedor extends \Eloquent {

public function proveedorable () {
    return $this->morphTo('proveedorable', 'proveedorable_type', 'proveedorable_id');
}

And this is the specific model:

这是具体的模型:

namespace App\Models\Proveedores;

class ProveedorTerminacion extends \Eloquent {

public function proveedor () {
    return $this->morphOne ('App\Models\Proveedores\Proveedor', 'proveedorable', 'proveedorable_type', 'proveedorable_id');
}

This way I'm trying to save a Proveedorassociated with a specific ProveedorTerminacionmodel, but for some reason a row for ProveedorTerminacionis created in my table, but not for Proveedorand Laravel won't show any error and return an empty response, what's wrong?

这样我试图保存一个Proveedor与特定ProveedorTerminacion模型相关联的,但由于某种原因,ProveedorTerminacion在我的表中创建了一行,但不是 forProveedor并且 Laravel 不会显示任何错误并返回一个空响应,有什么问题?

$terminador = ProveedorTerminacion::create (Input::all());

$proveedor = new Proveedor;
$proveedor->fill (Input::all());

$proveedor->proveedorable()->associate ($terminador);

$proveedor->save ();

回答by Jarek Tkaczyk

Associate method doesn't work correctly with morphTo, as it is never setting morphable_type, so don't use it. I'm pretty sure your code should throw fatal error because of that by the way. It requires bugfix.

Associate 方法不能与 morphTo 一起正常工作,因为它从不设置 morphable_type,所以不要使用它。顺便说一下,我很确定你的代码应该抛出致命错误。它需要修正错误。

Instead invert creating the relation and do it in the context of morphable object:

而是反转创建关系并在可变形对象的上下文中执行此操作:

$terminador = ProveedorTerminacion::create (Input::all());

$proveedor = new Proveedor;
$proveedor->fill (Input::all());

$terminador->proveedor()->save($proveedor);


I'm fixing that and going to send a PR to the laravel repo after some testing. I'll update my answer when it's done.

我正在解决这个问题,并在经过一些测试后将 PR 发送到 laravel 存储库。完成后我会更新我的答案。

Here it is: https://github.com/laravel/framework/pull/4249

这是:https: //github.com/laravel/framework/pull/4249