Ily*_* Vo 86 laravel eloquent laravel-4
我有两个相关的模型:Category和Post.
该Post模型具有published范围(方法scopePublished()).
当我尝试获取该范围的所有类别时:
$categories = Category::with('posts')->published()->get();
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
调用未定义的方法
published()
类别:
class Category extends \Eloquent
{
public function posts()
{
return $this->HasMany('Post');
}
}
Run Code Online (Sandbox Code Playgroud)
帖子:
class Post extends \Eloquent
{
public function category()
{
return $this->belongsTo('Category');
}
public function scopePublished($query)
{
return $query->where('published', 1);
}
}
Run Code Online (Sandbox Code Playgroud)
Jar*_*zyk 159
你可以内联:
$categories = Category::with(['posts' => function ($q) {
$q->published();
}])->get();
Run Code Online (Sandbox Code Playgroud)
您还可以定义关系:
public function postsPublished()
{
return $this->hasMany('Post')->published();
// or this way:
// return $this->posts()->published();
}
Run Code Online (Sandbox Code Playgroud)
然后:
//all posts
$category->posts;
// published only
$category->postsPublished;
// eager loading
$categories->with('postsPublished')->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56938 次 |
| 最近记录: |