Laravel 4-高级功能
我正在尝试检索Posts
具有$keyword
确定性的东西Companion
,此外,我还想检索Posts
具有链接title
或content
为的东西$keyword
。但是,当我尝试在内部使用where
或时,查询并未将这些因素考虑在内。当状态为0(不可见)或不在类别1内时,不应选择“过帐”项目。whereIn
whereHas
$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%' )->lists('id');
下面的代码块必须做两件事:
Post
带有title
或content
的项目$keyword
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();
上面的代码成功检索数据,除了中的where
和whereIn
部分whereHas
。
谁能帮助我?
感谢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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句