Home > OS >  I want to change my laravel database query to model relationship query for search data from database
I want to change my laravel database query to model relationship query for search data from database

Time:03-15

I am learning laravel Eloquent relationship, I successfully created a relationship between models for eq city belongsTo State and belongsTo country.

public function state(){

    return $this->belongsTo(State::class,'state_id', 'sr_id');
}

public function country(){

    return $this->belongsTo(Country::class,'country_id', 'sr_id');
}

this is my old search code, I want to know how we search data using model relationship method, how we call each columns from their following table.

$city = city::leftjoin('master_country','master_country.sr_id','=','master_city.country_id')
         ->leftjoin('master_state','master_state.sr_id','=','master_city.state_id')
         ->where('master_city.sr_status',0)
         ->where('master_city.sr_id','LIKE','%'.$query.'%')
         ->orWhere('master_city.sr_name','LIKE','%'.$query.'%')
         ->orWhere('master_city.city_tel_code','LIKE','%'.$query.'%')
         ->orWhere('master_country.sr_name','LIKE','%'.$query.'%')
         ->orWhere('master_state.sr_name','LIKE','%'.$query.'%')
         ->orderBy('master_city.sr_id')
         ->paginate(3,array('master_city.*','master_country.sr_name AS c_name','master_state.sr_name As s_name')); 

so it would we like..

City::with('state','country')->where etc 

CodePudding user response:

You can have a look at Constraining Eager Loads

$cities = City::with(
    [
        'state' => function ($query) {
            $query->where('state_column', 'some_value');
        },
        'country' => function ($query) {
            $query->where('country_column', 'some_value');
        }
    ]
)->get();

If you don't want to retrieve the relation data, you can use the whereHas() method:

City::whereHas('state', fn (Builder $builder) => $builder->where('state_column', 'some_value')));

Using arrow function is not required.

More documentation on this

  • Related