亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

調用未定義的方法 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 關注
  • 216 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號