Associating a child model in a polymorphic relationship causes an infinite loop?

不打扰是莪最后的温柔 提交于 2019-12-12 21:24:35

问题


I have a base Message class for an inbox using a polymorphic relationship to attach custom message types which all implement the same interface and behave differently in views based on their type. Display of that all works swimmingly, but I hit a snag when I tried to actually add these with code.

This is the Message class:

<?php

class Message extends Eloquent {
    public function author() {
        $this->belongsTo("User", "author_id");
    }

    public function recipient() {
        $this->belongsTo("User", "recipient_id");
    }

    public function message() {
        $this->morphTo();
    }
}

The model that I attach to message() implements MessageInterface, So I thought I'd be able to make a quick helper to attach this model's relationship via Message::send():

public static function send(MessageInterface $message, User $to, User $from) {
    if (! $message->exists)
        $message->save();

    $parent = new static;

    $parent->author()->associate($from);
    $parent->recipient()->associate($to);
    $parent->message()->associate($message); // line that errors

    return $parent->save();
}

But this ends up throwing what looks to be infinite recursion at me:

FatalErrorException: Maximum function nesting level of '100' reached, aborting!

This is the studly function, and from some searching it seems to happen when two models reference each other.

The Schema for the messages table is:

$table->increments("id");
$table->integer("message_id")->unsigned();
$table->string("message_type");
$table->integer("recipient_id")->unsigned();
$table->integer("author_id")->unsigned();
$table->timestamps();

Am I just doing something really wrong, here? I've looked through the morphTo method call in the source and tried seeing if reflection is the problem here (grabbing the function name and snake casing it), but I can't seem to find what is happening. The associate method call is just setting attributes and getting the class name for message_type, then returning a relationship.

There's no useful information in the error; it's a Symfony\Component\Debug\Exception\FatalErrorException with no context.

I'm running Laravel 4.1

来源:https://stackoverflow.com/questions/23779346/associating-a-child-model-in-a-polymorphic-relationship-causes-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!