简体   繁体   中英

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.

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. eg

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.

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 withoutforeign key constraint .

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

It works for me perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM