سؤال

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

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 Proveedor associated with a specific ProveedorTerminacion model, but for some reason a row for ProveedorTerminacion is created in my table, but not for Proveedor and Laravel won't show any error and return an empty response, what's wrong?

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

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

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

$proveedor->save ();
هل كانت مفيدة؟

المحلول

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.

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.

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top