Laravel 5.2关系:试图获得非对象的属性

时间:2016-07-06 16:01:31

标签: laravel-5

我有两种模式:Term和Post。

Term模型代表类别和标签。 帖子只能属于一个类别,它可以有很多标签(我对类别和标签使用相同的数据库表)。

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');
    }
}

在CategoryController中我有:

 class CategoryController extends Controller
 {


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


      public function getPostsOfAllCategories()
      {
          //
      }
 }

当我尝试使用slug event检索类别event的帖子时(在db中,类别和其中的一个帖子存在,以及mydb_posts_terms中的相应行)我获得

 Trying to get property of non-object

修改

我通过获取相同的$posts = Term::find($id)->posts()->get();获得Call to a member function$posts = Term::find($id)->posts;来尝试Trying to get property of non-object

在db中我有:

mydb_terms

| id | name  | slug  |   type   | created_at         | updated_at
| 1  | event | event | category | 2016-07-01 18:00:00| 2016-07-01 18:00:00

mydb_posts

| id | title   | content   | created_at         | updated_at
| 1  | A title | a content | 2016-07-04 17:20:12| 2016-07-04 17:20:12

mydb_posts_terms

| post_id | term_id   | order   | created_at         | updated_at
| 1       |   1       |   0     | 2016-07-06 14:13:43| 2016-07-06 14:13:43

0 个答案:

没有答案