Answer the question
In order to leave comments, you need to log in
Error when trying to get related data from another model, how to fix?
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.article_id' in 'where clause' (SQL: select * from `categories` where `categories`.`article_id` = 1 and `categories`.`article_id` is not null limit 1)
Previous exceptions
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.article_id' in 'where clause' (42S22)
$article= Article::find(1);
$title=$article->category;
dd($title);
----------------------------
файл article
public function category(){
return $this->hasOne('App\Category');
}
файл category
public function article(){
return $this->belongsTo('App\Article');
}
Answer the question
In order to leave comments, you need to log in
Most likely, you have a parent and daughter mixed up in a relationship.
In addition, for some reason you have a one-to-one relationship, although judging by the names of the classes (Article and Category), the relationship should be one-to-many (one category can contain many articles, and one article belongs to only one category).
It should be something like this:
// Category.php
public function articles(){
return $this->hasMany('App\Article');
}
// Article.php
public function category(){
return $this->belongsTo('App\Category');
}
categories:
- id
- name
- slug
articles:
- id
- category_id
- title
- content
$article = Article::find(1); // Получаем статью с ID 1
$category = $article->category; // Получаем категорию статьи
dump($category->name); // Выводим название категории
dump($category->articles); // Выводим список всех статей в данной категории
Try explicitly specifying foreign_key and local_key in the relays
https://laravel.com/docs/5.8/eloquent-relationship...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question