创建新条目(一对一多态关系)

时间:2020-05-25 14:40:19

标签: laravel eloquent

前提

我正在使用用户个人资料创建一个小型应用程序,该应用程序可以托管不同类型的项目列表。

每个Item可以是LinkCardVideo。因此,可以相应地优化每个布局。如果您喜欢的话,有点像Tumblr。

设置

出于这个原因,我选择使用一对一的多态关系(也许是过分杀伤力的),而items表具有诸如position之类的其他列(因此,用户可以重新订购商品。

items 表:

id
user_id (foreign key)
itemable_id
itemable_type
position
...

我的模型如下:

Item 模型

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

public function user()
    ...

Link 模型

public function item()
    {
        return $this->morphOne('\App\Item', 'itemable');
    }

public function user()
    ...

Card 模型

public function item()
    {
        return $this->morphOne('\App\Item', 'itemable');
    }

public function user()
    ...

...,对于其他Item类型,依此类推。

最后,在ItemController中,我将创建一个虚拟链接用于调试:

    // ...

    $newLink = new Link();
    $newLink->url = 'example.org';
    $newLink->title = 'Example Website NEW';
    $newLink->user_id = $user->id;

    $user->items()->save($newLink);

    // ...

但是,与我的预期不同,items表中的新条目未创建。相反,我必须自己做一次,一旦我存储了$newLink链接。

问题

这正常吗?我本来会期望自动创建Link(带有itemable_iditemable_type的。

如果是这样,我肯定在这里缺少什么。如何让Laravel自动创建items条目?

1 个答案:

答案 0 :(得分:0)

使用RewriteEngine On RewriteRule ^((?!index\.php).+)$ /index.php [L,QSA] ,如下所示:

associate