S
S
Sergey Khlopov2019-08-27 10:48:01
Laravel
Sergey Khlopov, 2019-08-27 10:48:01

How to make a one-to-one connection?

Hello, tell me please, I have two models:

  1. Category
  2. Image

I would like to make a one-to-one relationship between Category and Image, because a category can only have one image
. In the categories migration, there is this:
$table->unsignedBigInteger('image_id')->nullable();
$table->foreign('image_id')->references('id')->on('images'); //id картинки

This is the Category model
class Category extends Model
{
    public function image() //Вернёт картинку категории
    {
        return $this->hasOne('App\Models\Admin\Image');
    }
}

This is the Image model
class Image extends Model
{
    public function category() //Получить категорию
    {
        return $this->belongsTo('App\Models\Admin\Category');
    }
}

But in fact, the image method from Category does not return a category image, no matter what I try, tell me please what can be changed here?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question