【问题标题】:Category relationship is giving error when I try to acces category through post当我尝试通过帖子访问类别时,类别关系出错
【发布时间】:2018-01-19 22:04:49
【问题描述】:

当我尝试访问文章 vie 类别时,它在这里正常工作是 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 where category.article_id = 1 和category.article_id 不为空限制1)(查看:C:\wamp64\www\loremipsum\bluhbluhbluh\articleByTag.blade.php)

顺便说一句,我在创建文章时为article_category 保存关系的方式是

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

【问题讨论】:

    标签: mysql laravel laravel-5.4


    【解决方案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
    

    【讨论】:

    • 但你不觉得我不会做很多事情吗,比如计算关系和给出推荐列表之类的东西?
    • @Nikonah 你可以做同样的事情。
    • 这是我最终没有在文章表中保存类别 ID 的唯一原因。感觉更难相处
    • @Nikonah 这不是重新发明轮子并使用多对多而不是一对多的理由。使用一对多的关系实际上更容易。而且速度也更快。
    • 出于某种原因,我对此不太满意,但效果很好
    【解决方案2】:

    您的关系建立不正确。删除中间表并将category_id 添加到articles 表中。

    【讨论】:

    • Bu 文章可能只有 1 个类别
    • 那你有一对多,不需要article_category中间表。
    • 嗯,我认为这是正确的,但即使我在category model 中创建belongstomany,它仍然不允许我访问$article->category->name。当我写 $article->category 时,它也给了我它的关系,但是当我尝试获取 name 时,它说 此集合实例上不存在属性 [名称]。
    • 那是因为它现在是多对多的,你会有很多类别。因此,您必须执行$article->categories->each->name 之类的操作。但你真的想要我的回答中描述的一对多。
    【解决方案3】:

    关系设置不正确

    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();
    

    【讨论】:

    • 这不起作用。我真的认为该错误可能是由我拥有的表名引起的。他们的名字是:artilcecategoryarticle_category
    • 当我尝试这个时,双向都会出错。无法通过文章访问分类,也无法通过分类访问文章
    • @Nikonah 不再需要article_category,因为他们没有多对多关系
    • 数据库中的文章表的名称是什么?文章或文章?
    • article 和类别是category
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2021-11-28
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多