mercredi 6 juillet 2016

Laravel 5.2 relationships: Trying to get property of non-object

I have two models: Term and Post.

The Term model represents both categories and tags. A post can belong only to a category and it can have many tags (I use the same db table for categories and tags).

class Term extends Model
{

    protected $table = 'mydb_terms';

    public $timestamps = true;

    public function getRouteKeyName() {
       return 'slug';
    }

    public function posts(){
       return $this -> hasMany('Post');
    }
}


class Post extends Model
{
    use SoftDeletes;

    protected $table = 'mydb_posts';

    public $timestamps = true;


    public function category(){
       return $this -> belongsTo('Term','mydb_posts_terms', 'post_id', 'term_id') 
          -> withPivot('order') -> withTimestamps() -> where('type','category');
    }

    public function tags(){
       return $this -> hasMany('Term') -> where('type','tag');
    }
}

In the CategoryController I have:

 class CategoryController extends Controller
 {


      public function getPostsOfCategory($id)
      {
          $posts = Term::find($id)->posts->get();
      }


      public function getPostsOfAllCategories()
      {
          //
      }
 }

When I try to retrieve the posts of category event with slug event (in the db the category and one post in it exist, and also the corresponding row in mydb_posts_terms) I obtain

 Trying to get property of non-object



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire