mardi 6 mars 2018

Having problems nesting where clausing when querying the Database - Laravel

I'm having a problem querying the database.

My database is as follows:

Table Orders:

  • ordernumber
  • secondordernumber
  • deleted
  • created_at
  • user_id
    • Table users:
    • username
    • dealername

I've allready made the model relations from orders to users.

public function user(){
    return $this->hasOne('App\User','id','user_id');
}

How i am constructing my Query:

$query = Order::query();

$query->where('deleted', 0);

$fields = array('user' => ['username','dealername'], 'ordernumber', 'ordernumber_second');

foreach ($fields as $relation => $field) {
    if (is_array($field)){
        $query->whereHas($relation, function ($q) use ($field, $searchquery) {
            $q->where(function ($q) use ($field, $searchquery) {
                foreach ($field as $relatedField){
                    $q->orWhere($relatedField, 'like', "%{$searchquery}%");
                } 
            });
        });
    } else {
        $query->orWhere($field, 'like', "%{$searchquery}%");
    }
}


$orders = $query->orderBy('created_at','desc')->get();

// return view ETC

This works and all, the only this that is not working is the where clause:

$query->where('deleted', 0);

Is not working properly, the query is returning all records even if deleted is true..

It probably has something to do with the orWhere earlier on but i can't figure it out.

What i tried:

  • putting the where('deleted' , 0); on other places
  • Nesting the $query inside the else

Any help is appreciated



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2FeuN9Y
via IFTTT

Aucun commentaire:

Enregistrer un commentaire