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

牢牢

Laravel 4-高级功能

我正在尝试检索Posts具有$keyword确定性的东西Companion,此外,我还想检索Posts具有链接titlecontent为的东西$keyword但是,当我尝试在内部使用where或时,查询并未将这些因素考虑在内。当状态为0(不可见)或不在类别1内时,不应选择“过帐”项目。whereInwhereHas

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

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

  1. 搜索Post带有titlecontent的项目$keyword
  2. 搜索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();

上面的代码成功检索数据,除了中的wherewhereIn部分whereHas

谁能帮助我?

牢牢

感谢Jarek Tkaczyk。他的回答几乎是正确的。我所要做的就是把where里面的东西包起来orWhere现在我得到了Posts具有的Companion$keyword而我得到了Posts具有$keyword内部的contenttitle

$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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章