调用未定义的方法 BelongsTo::attach()

为什么这种关系不起作用?


我正在尝试使用 laravel 5.2、mysql、migrations 和 seeders 关联帖子和类别。


但我收到一个错误:


调用未定义的方法 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);

}


慕田峪7331174
浏览 218回答 1
1回答

30秒到达战场

belongsToMany 在模型中定义关系public function category(){  return $this->belongsToMany(Category::class);}不要忘记为Post和Category 关联添加一个中间数据透视表因为你没有 RTFM,这里有一个完整的工作示例PostTableSeeder.phppublic 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');});希望这可以帮助 :)
打开App,查看更多内容
随时随地看视频慕课网APP