Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel one to one relationship without foreign key

I have two tables the posts table and the categories table.

Each post has one category only.

What I am trying to do

Connect each post with one category ID without a foreign key.

Why I am trying to do this

Because I don't want to duplicate in every post the category word I just want to duplicate the category ID.

PostsController.php code

$posts = Post::orderBy('id', 'DESC') -> limit(16) -> get();

@foreach($posts as $post)

dd($post -> categories() -> cat);

@endforeach

Posts.php model code

class Post extends Model
{
    public function category() {
        return $this->hasOne('App\Category');
    }
}

Problem

I get an error to ask me for foreign key while I don't have foreign key in the categories table.

like image 327
user7431257 Avatar asked Mar 11 '17 10:03

user7431257


2 Answers

It's not necessary to have FK relationship. If you have a way to tell Laravel about how to find related record, it can do it for you. e.g.

class Post extends Model
{
    public function category() {
        return $this->hasOne('App\Category','id','category_id');
    }
}

Above will tell Laravel that when you ask for category property in post, it should take category_id from post table & look for id in category table. If both matches, it will give you matched category.

like image 185
Dhrumil Bhankhar Avatar answered Oct 03 '22 05:10

Dhrumil Bhankhar


Relation should be belongsTo():

public function category() {
    return $this->belongsTo('App\Category');
}

And the posts table should have category_id anyway to make it work, however you can use it without foreign key constraint.

like image 20
Alexey Mezenin Avatar answered Oct 03 '22 05:10

Alexey Mezenin