加入具有条件的Eloquent模型

时间:2015-08-18 15:38:31

标签: php laravel orm eloquent laravel-5.1

我有三个模型PostPageCategory

每个Page分配给一个Category,每个Post分配给一个Page

我已经定义了模型中的关系。我现在要做的是使用Eloquent ORM获取所有Post - 来自具有特定Page的{​​{1}}的对象。所以基本上,在SQL中我需要像这样做

Category

我现在以某种方式试图对Eloquent做同样的事,但我被困住了。我目前的代码看起来像这样

select p.* from posts p INNER JOIN pages pa ON pa.id = p.page_id where p.created_time > '2015-08-18 00:00:00' and pa.categories_id = 1 and p.isVisible = 1 order by p.total_count desc limit 100

现在,我想添加类别,但我不知道该怎么做。我在这里尝试了这些步骤:

// Getting all the top posts from facebook for today.
/** @var Builder $topPosts */
$topPosts = Post::where('created_time', '>', Carbon::today()->toDateTimeString());
if ($type !== null) {
    $topPosts = $topPosts->where('type', $type);
}
return $topPosts->orderBy('total_count', 'desc')
    ->visible()
    ->take($limit)
    ->get();

和这一个

$topPosts = $topPosts->with(['page' => function($query) use($categoryId){
    $query->where('page_categories_id', $categoryId);
}]);

但它们都没有奏效。我怎么做到这一点?我总是收到错误消息

  

SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'categories_id'(SQL:select * from $topPosts = $topPosts->with('page')->where('page_categories_id', $categoryId); 其中posts> 2015-08-18 00:00 :00 created_time = 1和categories_id = 1个订单isVisible desc limit 100)

1 个答案:

答案 0 :(得分:1)

看起来您需要whereHas()使用with()语句(http://laravel.com/docs/4.2/eloquent#querying-relations

这应该可行,并且基本上只是查询具有特定category_id的关联Pages的帖子。我没有包括你的订购和事情..

$posts = Post::where('created_time', '>', Carbon::today()) // Eloquent shouldn't actually need the toDateTimeString()
            ->with('page') // leave this in to eager load the page
            ->whereHas('page', function($query) use ($categoryId) {
                $query->where('page_categories_id', $categoryId);
            })
            ->get();