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. 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With