O
O
ortsuev332019-08-22 12:27:18
Laravel
ortsuev33, 2019-08-22 12:27:18

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)

Error when trying to get related data from another model, how to fix?
$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

2 answer(s)
R
Razgelday, 2019-08-25
@ortsuev33

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');
}

Then the database structure should be like this:
categories:
   - id
   - name
   - slug

articles:
   - id
   - category_id
   - title
   - content

Relationships can be used like this:
$article = Article::find(1); // Получаем статью с ID 1

$category = $article->category; // Получаем категорию статьи

dump($category->name); // Выводим название категории

dump($category->articles); // Выводим список всех статей в данной категории

D
Daria Motorina, 2019-08-22
@glaphire

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 question

Ask a Question

731 491 924 answers to any question