当我尝试通过类别访问文章时,它可以正常工作,这里是 category.php
模型
public function articles(){
return $this->belongsToMany('App\Article');
}
但是当我尝试访问类别名称查看文章时,它无法按预期工作,我在那里犯了错误并试图修复它,但到目前为止还没有运气。这是文章模型
public function category(){
return $this->hasOne('App\category');
}
并且有一个用于将这两者相互关联的表,在页面中称为 article_category
,我在其中获取给定标签的所有文章,我想做类似 $article-> 的操作类别->名称
有一些东西对我来说听起来非常错误,但我无法弄清楚。
我收到的错误是
Column not found: 1054 Unknown column 'category.article_id' in 'where clause' (SQL: select * from
category
wherecategory
.article_id
= 1 andcategory
.article_id
is not null limit 1) (View: C:\wamp64\www\loremipsum\bluhbluhbluh\articleByTag.blade.php)
顺便说一句,我在创建文章时保存 article_category
关系的方式是
$article->category()->sync($request->category, false);
最佳答案
您说过该文章可能只有一个类别。在本例中,删除数据透视表并将 category_id
添加到 articles
表中。
然后在Article
模型中定义这个关系:
public function category()
{
return $this->belongsTo(Category::class);
}
在Category
模型中:
public function articles()
{
return $this->hasMany(Article::class);
}
执行此操作后,您将能够通过以下方式访问文章的类别:
$article->category->name
关于mysql - 当我尝试通过帖子访问类别时,类别关系出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342145/