X
X
xnkka2019-12-11 14:23:00
Laravel
xnkka, 2019-12-11 14:23:00

How to properly organize queries to a database with a dynamic number of conditions?

There is such a clumsy (xs how to write it using relays) query to the database,

$ads = DB::table('ads')
            ->join('ad_translates','ads.id','=','ad_translates.ad_id')
            ->join('users', 'ads.user_id', '=', 'users.id')
            ->join('cities', 'ads.city_id', '=', 'cities.id')
            ->join('country_translates', 'cities.country_id', '=', 'country_translates.country_id')
            ->join('city_translates', 'ads.city_id', '=', 'city_translates.city_id')
            ->join('category_translates', 'ads.category_id', '=', 'category_translates.category_id')
            ->Where('country_translates.language_id', $lang_id)
            ->Where('city_translates.language_id', $lang_id)
            ->Where('category_translates.language_id', $lang_id)
            ->where('country_translates.country_id',$country_id)
            ->where('cities.id',$city_id)
            ->select('ads.*','ad_translates.name','ad_translates.description','users.name AS username', 'country_translates.country_id AS country_id',
                'country_translates.name AS country', 'city_translates.name AS city', 'category_translates.name AS category')
            ->paginate(3);

In this query, the conditions
->where('country_translates.country_id',$country_id)
->where('cities.id',$city_id)

may be completely absent, or only one condition c country_id may be present. It turns out 3 situations when there are no conditions, one condition or two conditions. How to organize it in code so that it is kosher

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RMate, 2019-12-11
@xnkka

$arr = [
  ['first_name', '=', 'last_name'],
  ['updated_at', '>', 'created_at']
];
$users = DB::table('users')->whereColumn($arr)->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question