执行$query->时,正在使用语句更新对象状态;where(),所以当您进行第二次选择时,第一次选择的所有条件仍然存在。这就是为什么这些行在没有任何任务的情况下工作的原因:
if($cat) $query->where('cat',$cat);
if($year) $query->where('jahrprod',$year);
要实现所描述的行为,您需要创建查询对象副本:
$query = Pic::where('pics.user_id',$user->id);
if($cat) $query->where('cat',$cat);
if($year) $query->where('jahrprod',$year);
$queryClone = clone $query;
$zb = $query->select('pics.id','pics.title','pics.created_at')
->where('pics.id', '>', $pic->id)
->orderBy('pics.id')
->take(2)
->get()->reverse();
$za = $queryClone->select('pics.id','pics.title','pics.created_at')
->where('pics.id', '<', $pic->id)
->orderBy('pics.id')
->take(13)
->get();
请注意,单纯的分配在这里是行不通的:
$queryClone = $query;
因为这将传递对象引用,并导致与您的情况相同的行为。克隆将创建完整的对象副本。
http://php.net/manual/en/language.oop5.cloning.php