Laravel 4:在哪里和哪里在哪里使用Eloquent

时间:2015-02-09 23:39:33

标签: laravel-4 eloquent

Laravel 4 - 先进的地方

我正在尝试检索Posts $keyword某个Companion的{​​{1}},除此之外,我想要检索Posts的链接{{1}或title作为content。 但是,当我尝试在$keyword内使用wherewhereIn时,查询不会考虑这些因素。当状态为0(不可见)或不属于类别1时,不应选择Post项目。

whereHas

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

  1. 使用$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%' )->lists('id'); Post title
  2. 搜索content个项目
  3. 搜索$keyword <{1}} <{1}}的{​​{1}}个项目

    代码:

    Post

    上述代码成功检索数据,但Companions内的$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(); 部分除外。

    谁能帮助我?

2 个答案:

答案 0 :(得分:2)

  1. orWhere条款包含在(..)
  2. where关闭时您不需要whereInwhereHas,因为它会查询companions
  3. whereIn你不需要category_id,除非你想传递多个ID
  4. $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();
    

答案 1 :(得分:1)

感谢Jarek Tkaczyk。 他的回答几乎是正确的。我所要做的就是将where包裹在orWhere内。现在,我得到的Posts Companion$keyword类似Posts $keyword content title$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(); {1}}。

{{1}}