首页 > 解决方案 > 调用未定义的方法 BelongsTo::attach()

问题描述

为什么关系不好?

我正在尝试使用 laravel 5.2、mysql、迁移和播种机来关联帖子和类别。

但我收到一个错误:

调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsTo::attach()

PostTableSeeder.php

public function run()
{
    factory(App\Post::class, 300)->create()->each(function (App\Post $post) {
        $post->category()->attach([
            rand(1, 5),
            rand(6, 14),
            rand(15, 20),

        ]);
    });
}

模型:Post.php

public function category()
{
  return $this->belongsTo(Category::class);
}

模型:Category.php

public function posts()
{
  return $this->belongsTo(Post::class);
}

标签: phpmysqllaravel

解决方案


在模型中定义belongsToMany 关系

public function category()
{
  return $this->belongsToMany(Category::class);
}

不要忘记为PostCategory 关联添加中间数据透视表

由于您不使用 RTFM,因此这是一个完整的工作示例

PostTableSeeder.php

public function run()
{
    factory(App\Post::class, 300)->create()->each(function (App\Post $post) {
        $post->categories()->attach([
            rand(1, 5),
            rand(6, 14),
            rand(15, 20),
        ]);
    });
}

Post.php模型

public function categories()
{
  return $this->belongsToMany('App\Category');
}

Category.php模型

public function posts()
{
  return $this->belongsToMany('App\Category');
}

category_post表迁移

Schema::create('category_post', function (Blueprint $table) {
    $table->unsignedBigInteger('post_id');
    $table->unsignedBigInteger('category_id');
});

希望这可以帮助 :)


推荐阅读