Saturday, March 11, 2017

Laravel one to one relationship without foreign key

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

Each post have 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 duplicated 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');
    }
}



via user7431257

Advertisement