我正在尝试与 Laravel 建立多态关系。我已经阅读了文档并查看了相关代码,但似乎无法让所有这些都正常工作。我试图附加photos
到rooms
一个房间可以有很多照片的地方。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)的问题,但这似乎不是这里的问题。