3

我正在尝试与 Laravel 建立多态关系。我已经阅读了文档并查看了相关代码,但似乎无法让所有这些都正常工作。我试图附加photosrooms一个房间可以有很多照片的地方。type与关系相关联的作品,但id总是0

为什么它的一部分会起作用,有人可以指出我的关系中有什么问题吗?

我相信这个问题与我如何在表中创建数据有关:

$photo = new Photo;
$photo->URL = 'thePhotoURL.extension';
$photo->save();

$room = new Room;
$room->name = 'Some Room Name';
// seems weird to me that I "save" the photo twice
// or am I just saving the relationship here?
// have tried the other relationship options too (associate, attach, synch)
$room->photos()->save($photo);
// have also tried:
// $room->photos()->save(new Photo(array('URL' => 'urlTest.com')));
// get error "URL"

$room->save();

创建照片表:

public function up() {
    Schema::create('photos', function($t) {

        $t->increments('id');

        // ... ...
        // the Id is always 0 but the type is correct
        $t->integer('imageable_id');
        $t->string('imageable_type');

        $t->softDeletes();
        $t->timestamps();

    });
}

还有我的课,

照片:

class Photo extends Eloquent {
    public function imageable() {
        return $this->morphTo();
    }
}

房间:

class Room extends Eloquent {       
    public function photos() {
        return $this->morphMany('Photo', 'imageable');
    }
}

我已经看到保留字(如 Event)的问题,但这似乎不是这里的问题。

4

2 回答 2

8

$room->photos()->save($photo);保存原件后需要运行。原件尚不存在,因此没有可关联的 ID。

也许它应该抛出一个异常,也许不是。就个人而言,我宁愿它对我尖叫。

于 2013-09-09T14:38:00.497 回答
4

用这个:

$photo = $room->photos()->create(array('URL' => 'thePhotoURL.extension'));

于 2014-02-11T22:13:34.910 回答