سؤال

Is it possible to split queries somehow like this?

public function getStatuses($dates)
{
    $query = DB::table('tickets');

    if ($dates['from'])
        $query = $query->where('from', $dates['from']);

    if ($dates['to'])
        $query = $query->where('to', $dates['to']);

    $query = $query->select('Active');

    return $query->get()->toArray();
}
هل كانت مفيدة؟

المحلول

Yes, it's possibile. But don't reassign to the same variable or you risk messing it up:

public function getStatuses($dates)
{
    $query = DB::table('tickets');
    if ($dates['from'])
        $query->where('from', $dates['from']);
    if ($dates['to'])
        $query->where('to', $dates['to']);
    $query->select('Active');
    return $query->get()->toArray();
}

نصائح أخرى

In Laravel 4, its necessary to assign the get method to a variable

public function scopeGetPosts($query, $this_user = NULL){
    $results = DB::table('post')
                ->select('*')
                ->where('post_status','=','publish');

    if( $this_user != NULL ){
        $results->where('post_author','=',$this_user->user_id);
    }

        $data = $results->orderBy('created_at', 'desc')
                ->get(); 

        if( empty( $results ) )
            $data = 'no results';

    return $data;
}

In Laravel Eloquent :

$query = ModelName::where('status',1);

if($userId){
 $query->where('user_id',$userId);
}

if($limit){
 $query->limit($limit);
}    

$result = $query->get();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top