Laravel 多对多多态关系 sql 播种时出错

Laravel many-to-many polymorphic relationships sql error while seeding

你好我的 foreach 循环 returns a Call to a member function bookmarkItems() on int,当我尝试为我的数据库做种时。我不明白我遗漏了什么 laravel docs poly relation I have setup the relationsships like this and then when I am trying to save the new bookmarkitem is returns the error. stack overflow post about saving 我试过 saveattach 但两者 return 都是同样的错误 我没有看到我在代码中遗漏了什么.

编辑:

看到 Post::all()->random()->id 应该 Post::all()->random() 它 return 是这个错误

SQLSTATE[HY000]: General error: 1364 Field 'bookmarks_id' doesn't have a 
default value (SQL: insert into `bookmark_items` (`bookmark_items_id`, 
`bookmark_items_type`) values (5, App\Models\Post))

什么意思在附加或保存新书签项时它不添加 $bookmarkItems->bookmarks_id = Bookmark::all()->random()->id; 导致它不将其插入数据库而我在将新书签项保存到数据库之前设置它?

迁移

    Schema::create('bookmark_items', function (Blueprint $table) {
        $table->id();
        $table->integer('bookmark_items_id')->unsigned();
        $table->string('bookmark_items_type');
        $table->unsignedBigInteger('bookmarks_id');
        $table->foreign('bookmarks_id')->references('id')->on('bookmarks');
        $table->timestamps();
    });

class Post extends Model
{
    public function bookmarkItems()
    {
         return $this->morphToMany(BookmarkItems::class, 'bookmark_items');
    }
}

class Comment extends Model
{
     public function bookmarkItems()
    {
        return $this->morphToMany(BookmarkItems::class, 'bookmark_items');
    }
}


class BookmarkItems extends Model
{

    public function posts(): \Illuminate\Database\Eloquent\Relations\MorphToMany
    {
        return $this->morphedByMany(Post::class, 'bookmark_items');
    }


    public function comments(): \Illuminate\Database\Eloquent\Relations\MorphToMany
    {
        return $this->morphedByMany(Comment::class, 'bookmark_items');
    }
}

Foreach 函数

   foreach ((range(1, 6)) as $index) {
       $post = Post::all()->random()->id;
       $bookmarkItems = new BookmarkItems();
       $bookmarkItems->bookmarks_id = Bookmark::all()->random()->id;
       $post->bookmarkItems()->save($bookmarkItems);
   }

https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships

$post->bookmarkItem()->attach($bookmarkItem, ['bookmarks_id' => Bookmark::all()->random()->id]);

只需像这样提供要插入的附加数据bookmarks_id 所以最终结果会是这样

foreach ((range(1, 6)) as $index) {
        $post = Post::all()->random();
        $bookmarkItem = new BookmarkItem();
        $post->bookmarkItem()->attach($bookmarkItem, ['bookmarks_id' => Bookmark::all()->random()->id]);
}