IN statement in Eloquent

2019-02-27 11:11发布

I'm trying to execute IN statement in Eloquent query. I tried this:

$id = urldecode($id);

$news = News::whereHas('newsCategories', function($q) use($id)
{
    $q->where('category_id', 'IN', '('.$id.')')->orderBy('created_at', 'desc');
})->get();

But I get empty result.

When I switch IN for = and pass a number instead of array I get results. Did I do something wrong?

So this works:

$id = 2;

$news = News::whereHas('newsCategories', function($q) use($id)
{
    $q->where('category_id', '=', $id)->orderBy('created_at', 'desc');
})->get();

1条回答
做个烂人
2楼-- · 2019-02-27 11:31

You want whereIn with an array of your ids to be checked...

$news = News::whereHas('newsCategories', function($q) use($array_of_ids)
{
    $q->whereIn('category_id', $array_of_ids)
      ->orderBy('created_at', 'desc');
})->get();

Just make sure that you're passing in something that is truly an array :)

查看更多
登录 后发表回答