php - 调用未定义的方法 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);
}
解决方案
在模型中定义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');
});
希望这可以帮助 :)
推荐阅读
- java - JButton 不产生输出 - 石头剪刀布游戏(GUI、Java)
- mysql - MySQL 上的全文搜索:无法在连字符/破折号后按单词搜索
- wso2 - WSO2 通过 Web 服务进行身份验证
- c++ - 任何数据类型的 C++ 模板复制构造函数
- python - 如何在 Django 中获取 Post 数据表单 Category?
- python - 如何在tensorflow的Estimator的input_fn中读取和处理我的图像文件?
- css - wordpress css sprite 加载图片
- node.js - Mongoose - 为字段的每个唯一值计算文档
- javascript - Javascript:访问单个元素时,对象数组返回未定义。即使其中保存了 696 个对象
- google-cloud-platform - 在 Google 数据洞察中的多个来源的单个页面中添加多个图表