mysql - 当我尝试通过帖子访问类别时,类别关系出现错误

标签 mysql laravel laravel-5.4

当我尝试通过类别访问文章时,它可以正常工作,这里是 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 where category.article_id = 1 and category.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/

相关文章:

mysql - 杀死 'copying to tmp table' 的复制 MySQL 进程是否安全?

php - Laravel 5.4 artisan 为/public 中的现有文件夹提供 htaccess/和 Routes::get

php - 在 Laravel 4 的 View 中使用 explode

laravel - 如何将 View 文件的html存储到laravel 5.4中的变量中?

php - Laravel:从 Mysql 查询到 Eloquent

mysql - 根据字段的组合权重对结果进行排序

javascript - 错误: read ECONNRESET when connected to a mysql server with Node.js

Mysql 使用 unixtime 值对时间戳进行选择时,日期时间值不正确

php - 调用未定义的方法 Illuminate\Auth\TokenGuard::attempt()

recursion - 在 Laravel 中使用 Baum 显示分层树/在 Laravel 中使用递归函数