【问题标题】:Laravel-4 Polymorphic Relationship Only Assigning the Type (not the Id)Laravel-4 多态关系仅分配类型(不是 Id)
【发布时间】:2013-09-13 00:52:46
【问题描述】:

我正在尝试与 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');
    }
}

我发现保留字 (like Event) 存在问题,但这似乎不是问题所在。

【问题讨论】:

    标签: laravel laravel-4 polymorphic-associations polymorphism


    【解决方案1】:

    使用这个:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • ...你有它。谢谢你。我知道他们为什么不这样做,但我希望他们抛出异常。如果你给 id 赋值为 0,那显然有问题!再次感谢!
      • 很高兴,希望你喜欢 Laravel!
      猜你喜欢
      • 1970-01-01
      • 2013-10-05
      • 2020-10-17
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2015-02-15
      • 2020-04-25
      • 1970-01-01
      相关资源
      最近更新 更多