当我尝试访问类别的文章时,它正常工作的是category.php
模型
public function articles(){
return $this->belongsToMany('App\Article');
}
但是当我尝试访问类别名称视图文章时它不能正常工作,我让我在那里弄错了并尝试修复它,但到目前为止没有运气。这是文章模型
public function category(){
return $this->hasOne('App\category');
}
并且有一个关于这两者的关系表,它在页面中被称为article_category
,我得到了给定标签的所有文章,我想做$article->category->name
这样的事情对我来说不对,但我无法理解。
我收到的错误是
找不到列:1054'where子句'中的未知列'category.article_id'(SQL:select * from
category
category
。article_id
= 1和{{1} }。category
不是空限制1)(查看:C:\ wamp64 \ www \ loremipsum \ bluhbluhbluh \ articleByTag.blade.php)
当我创建文章时,我保存article_id
关系的方式是
article_category
答案 0 :(得分:1)
您的关系建立不正确。删除中间表并将category_id
添加到文章表中。
答案 1 :(得分:1)
关系设置不正确
Category
模型应该像:
class Category extends Model
{
protected $table='category';
//give me all articles associated with the given category
public function articles()
{
return $this->hasMany('App\Article');
}
}
Article
模型
class Article extends Model
{
protected $table='article';
//get the category associated with the given article
public function category()
{
return $this->belongsTo('App\Category');
}
}
用于将文章附加到类别:
$article->category()->associate($category)->save();
答案 2 :(得分:1)
你说那篇文章可能只有一个类别。在这种情况下,请删除数据透视表并将category_id
添加到articles
表中。
然后在Article
模型中定义这种关系:
public function category()
{
return $this->belongsTo(Category::class);
}
在Category
模型中:
public function articles()
{
return $this->hasMany(Article::class);
}
当你这样做时,你将能够通过以下方式访问文章的类别:
$article->category->name