Home > database >  Getting value from a query
Getting value from a query

Time:11-03

I'm new to Laravel. I'm trying to get the objectives.id from this query but instead it's giving me the media.id, so trying to do an 'AS' in the query so I can pass it through to the view:

        $objectives = DB::table('objectives')
        ->join('users', 'objectives.assigned_id', '=', 'users.id')
        ->join('media', 'objectives.training_document_id', '=', 'media.model_id')
        ->where('objectives.assigned_id', '=', $assigned_id)
        ->where('media.model_type', '=', 'App\Models\TrainingDoc')
        ->distinct('objectives.id')
        ->get();

CodePudding user response:

You have to select the distinct objectives.id using the query which will return distinct set of objectives.ids.

$objectives = DB::table('objectives')
->select('objectives.id')->distinct()
->join('users', 'objectives.assigned_id', '=', 'users.id')
->join('media', 'objectives.training_document_id', '=', 'media.model_id')
->where('objectives.assigned_id', '=', $assigned_id)
->where('media.model_type', '=', 'App\Models\TrainingDoc')
->get();

If you want to get a one record per objectives.id you can use groupBy option which will return the whole row.

$objectives = DB::table('objectives')
->join('users', 'objectives.assigned_id', '=', 'users.id')
->join('media', 'objectives.training_document_id', '=', 'media.model_id')
->where('objectives.assigned_id', '=', $assigned_id)
->where('media.model_type', '=', 'App\Models\TrainingDoc')
->groupBy('objectives.id')
->get();

CodePudding user response:

foreach($objectives as $key=>$objective) dump($objective->id); endforeach

  • Related