category关系出现错误

dpiehjr4  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(301)

当我尝试访问文章vie类别时,它在这里正常工作 category.php 模型

public function articles(){
    return $this->belongsToMany('App\Article');
}

但是当我尝试访问category name视图文章时,它并没有像预期的那样工作,我犯了一个错误并试图修复它,但到目前为止没有任何运气。这是文章模型

public function category(){
    return $this->hasOne('App\category');
}

这里有一个表,用来表示这两个元素之间的关系,叫做 article_category 在获取给定标签的所有文章的页面中,我想执行以下操作 $article->category->name 有件事我听上去很不对劲,但我想不通。我收到的错误是
找不到列:“where子句”中的1054未知列“category.article\u id”(sql:select*from) category 哪里 category . article_id =1和 category . article_id 不是空限制1)(视图:c:\wamp64\www\loremipsum\bluhbluh\articlebytag.blade.php)
顺便说一句,我把这段感情留给 article_category 创建项目时

$article->category()->sync($request->category, false);
jk9hmnmh

jk9hmnmh1#

你的关系建立得不正确。删除中间表并添加 category_id 到文章表。

c9x0cxw0

c9x0cxw02#

关系设置不正确 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();
guicsvcw

guicsvcw3#

你说过那篇文章可能只有一个类别。在这种情况下,删除透视表并添加 category_id 进入 articles table。
然后在 Article 模型定义此关系:

public function category()
{
    return $this->belongsTo(Category::class);
}

而在 Category 型号:

public function articles()
{
    return $this->hasMany(Article::class);
}

完成此操作后,您将能够通过以下方式访问文章的类别:

$article->category->name

相关问题