Laravel,与雄辩的插入一对多的关系

时间:2021-12-30 20:16:16

I have a model Item with a has-many relationsship with points like this:

我有一个模型项目与这样的点有很多关系:

public function points() {
    return $this->has_many('Point');
}

Then in my controller I want to set some data when a user is posting an Item. So I do it like this:

然后在我的控制器中,我想在用户发布项目时设置一些数据。所以我这样做:

        $item = new Item;
        $item->author = $author;
        $item->description = '';
        $item->link = $link;
        $item->source = $url['host'];
        $item->title = $title;
        $item->url_encoded = $url;  
        $item->save(); 
        $points = array(
            array('ip' => $ip)
        );

        $item->points()->save($points);

However this gives me an error which I seem to get everytime I try to save a Point which is:

然而,这给了我一个错误,我似乎每次尝试保存一个点时得到的错误:

Array to string conversion

What can I do to insert my Point with the property item_id correct?

如何使用属性item_id插入我的Point是否正确?

1 个解决方案

#1


1  

After slowly going through the code line by line I noticed that the error occurred when saving the Item in the first place. A column had a variable that got overwritten by an array. Therefore I got this error message.

在逐行缓慢执行代码之后,我注意到在首先保存Item时发生了错误。列有一个被数组覆盖的变量。因此我收到此错误消息。

It was very confusing though because I added the new code when I added the Point. Since there was no trace from where the error came from it was an easy thing to miss.

这很令人困惑,因为我在添加Point时添加了新代码。由于错误来自哪里,因此很容易错过。

#1


1  

After slowly going through the code line by line I noticed that the error occurred when saving the Item in the first place. A column had a variable that got overwritten by an array. Therefore I got this error message.

在逐行缓慢执行代码之后,我注意到在首先保存Item时发生了错误。列有一个被数组覆盖的变量。因此我收到此错误消息。

It was very confusing though because I added the new code when I added the Point. Since there was no trace from where the error came from it was an easy thing to miss.

这很令人困惑,因为我在添加Point时添加了新代码。由于错误来自哪里,因此很容易错过。