smartest way for doing a query by orm to a model where a n:m relationship is involved

Viewed 16

I need to extract some datas from a table;

leves -----n-----m---company_levels----m---n---company

the cleanest way:

    $levels = Cga_company_level::where(['company_uuid' => $companyUuid])->get()->pluck('cgaLevel');

the second cleanest way:

            $levels = Cga_company_level::where(['company_uuid' => $companyUuid])->get();
            $levelIds= $companyLevelsByUuids->pluck('cga_level_id');
            $levels= Cga_level::whereIn('cga_level_id',$levelIds)->get();

the old school way:

$companyLevelsByUuids = Cga_company_level::where(['company_uuid' => $companyUuid])->with('cgaLevel')->get();
$levels = [];
foreach ($companyLevelsByUuids as $companyLevel) {
         $level = $companyLevel->cgaLevel;
         $levels[] = $level;
}

any other smartest way?

1 Answers

You can use the levels relationship to get it through a different way but it might not necessarily be more efficient. Plus, you'll be finding the company through the Id or alternatively use whereUuid($companyUuid)->first() in the following query:

$levels = Company::find($companyId)->levels->get()->pluck('cga_level_id');
Related