为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕田峪7331174 2021-12-24 15:45:43
为什么这种关系不起作用?我正在尝试使用 laravel 5.2、mysql、migrations 和 seeders 关联帖子和类别。但我收到一个错误:调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsTo::attach()PostTableSeeder.phppublic 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.phppublic function category(){  return $this->belongsTo(Category::class);}模型: Category.phppublic function posts(){  return $this->belongsTo(Post::class);}
查看完整描述

1 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

belongsToMany 在模型中定义关系


public function category()

{

  return $this->belongsToMany(Category::class);

}

不要忘记为Post和Category 关联添加一个中间数据透视表


因为你没有 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');

});

希望这可以帮助 :)


查看完整回答
反对 回复 2021-12-24
  • 1 回答
  • 0 关注
  • 217 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号