Laravel 4:whereHas 中的 where 和 whereIn 使用 Eloquent

Laravel 4: A where and whereIn inside a whereHas using Eloquent

Laravel 4 - 高级

我正在尝试检索具有 $keywordPosts,例如某个 Companion,除此之外,我还想检索具有链接 PostsPosts =18=] 或 content 作为 $keyword。 但是当我尝试在 whereHas 中使用 wherewhereIn 时,查询不会考虑这些。当状态为 0(不可见)或不在类别 1 内时,不应选择 Post 项目。

$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%' )->lists('id');

下面的代码块必须做两件事:

  1. 搜索 Post 个带有 titlecontent 的项目,例如 $keyword
  2. 搜索具有 CompanionsPost 项目,例如 $keyword

代码:

$results = Post::whereHas('companions', function($query) use($companion_id)
                {
                    $query->whereIn('companions.id', $companion_id)
                        ->where('state', '=', 1)
                        ->whereIn('category_id', array(1));
                })
                ->whereIn('category_id', array(1))
                ->orwhere('title', 'LIKE', '%' . $keyword . '%' )
                ->orWhere('content', 'LIKE', '%' . $keyword . '%' )
                ->where('state', '=', '1')
                ->orderBy('menu_order', 'desc')
                ->get();

除了whereHas中的wherewhereIn部分,上面的代码成功获取了数据。

谁能帮帮我?

  1. 将您的 orWhere 子句包装在 (..)
  2. whereHas 闭包中不需要 wherewhereIn,因为它查询 companions table
  3. 你不需要 whereIn 用于 category_id,除非你想在那里传递多个 ID

.

$results = Post::whereHas('companions', function($query) use($companion_id)
    {
        $query->whereIn('companions.id', $companion_id);
    })
    ->whereIn('category_id', array(1)) // why not where(..) ?
    ->where(function ($q) use ($keyword) {
      $q->where('title', 'LIKE', '%' . $keyword . '%' )
        ->orWhere('content', 'LIKE', '%' . $keyword . '%' );
    })
    ->where('state', '=', '1')
    ->orderBy('menu_order', 'desc')
    ->get();

感谢 Jarek Tkaczyk。 他的回答几乎是正确的。我所要做的就是将 where 包裹在 orWhere 中。现在我得到 Posts 有一个 Companion$keyword 我得到 Posts$keywordcontenttitle.

$results = Post::whereHas('companions', function($query) use($companion_id)
                {
                    $query->whereIn('companions.id', $companion_id)
                    ->where('state', '=', '1');
                })
                ->orWhere( function($q) use ( $keyword ) {
                    $q->where('title', 'LIKE', '%' . $keyword . '%' )
                      ->orWhere('content', 'LIKE', '%' . $keyword . '%' );
                })
                ->whereIn('category_id', array(1, 3))
                ->where('state', '=', '1')
                ->orderBy('menu_order', 'desc')
                ->get();