mardi 7 février 2017

Laravel retrieving data using relationships

I have one-to-one relationship between Post and Category. Let me try to illustrate columns. Post columns:

| id | pr_name | pr_description | ..... | `category_id`

And here is Category columns

| id | name 

So what am I trying to do is the following. Category is already defined by me and will have only names of Categories. I should retrieve the name of category in my Blade.php file using it's id like this: $post->category->name. But I get error: Trying to get property of non-object. Here are my models: Model of Post

class Post extends Model
{
  public function category()
  {
      return $this->hasOne('App\Like','id','category_id'); // 'id' is foreign key,
                                                           // 'category_id' is local key 
  }
}

Model of Category:

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



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kOWFWO
via IFTTT

Aucun commentaire:

Enregistrer un commentaire