Laravel 4 - 先进的地方
我正在尝试检索Posts
$keyword
某个Companion
的{{1}},除此之外,我想要检索Posts
的链接{{1}或title
作为content
。
但是,当我尝试在$keyword
内使用where
或whereIn
时,查询不会考虑这些因素。当状态为0(不可见)或不属于类别1时,不应选择Post项目。
whereHas
下面的代码块必须做两件事:
$companion_id = Companion::where('name', 'LIKE', '%' . $keyword . '%' )->lists('id');
或Post
title
content
个项目
$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();
部分除外。
谁能帮助我?
答案 0 :(得分:2)
orWhere
条款包含在(..)
where
关闭时您不需要whereIn
和whereHas
,因为它会查询companions
表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();
答案 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}}