拉拉维尔。在具有关系的模型中使用scope()

标签 laravel laravel-4 eloquent

我有两个相关模型:CategoryPost

Post 模型有一个 published 范围(方法 scopePublished())。

当我尝试获取该范围内的所有类别时:

$categories = Category::with('posts')->published()->get();

我收到错误:

Call to undefined method published()

类别:

class Category extends \Eloquent
{
    public function posts()
    {
        return $this->HasMany('Post');
    }
}

帖子:

class Post extends \Eloquent
{
   public function category()
   {
       return $this->belongsTo('Category');
   }


   public function scopePublished($query)
   {
       return $query->where('published', 1);
   }

}

最佳答案

您可以内联完成:

$categories = Category::with(['posts' => function ($q) {
  $q->published();
}])->get();

您还可以定义关系:

public function postsPublished()
{
   return $this->hasMany('Post')->published();
   // or this way:
   // return $this->posts()->published();
}

然后:

//all posts
$category->posts;

// published only
$category->postsPublished;

// eager loading
$categories->with('postsPublished')->get();

关于拉拉维尔。在具有关系的模型中使用scope(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26178315/

相关文章:

Laravel - Route::resource 与 Route::controller

php - Laravel 4 - 一个表单中的两个提交按钮,并且两个提交都由不同的操作处理

laravel - 调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsTo::save()

mysql - 试图将 Eloquent 查询限制为计数为 0 的关系

javascript - 如何在 Vue.js 中从 JSON 数据创建 select 元素?

mysql - Laravel 5.6 如何从列中获取重复数据

authentication - 带有 Route::resource 的“auth”中间件

php - barryvdh laravel dompdf 只渲染两页

php - Laravel Eloquent 集合上的 Array_unique

php - Laravel Eloquent 更新受影响的行数始终为 1