Kapitan Teemo
Kapitan Teemo

Reputation: 2164

Get only one column and create an alias for that column using "with()" function in laravel

I have two tables, JobOrder and Job. I'm using one-to-many relationship.

One Job can have many JobOrder and one JobOrder belongs to only one Job.

JobOrder Model:

public function job()
{
    return $this->belongsTo(Job::class);
}

Controller:

public function getAllJobOrder()
{
    $results = JobOrder::with('job')->get();
    return $results;
}

the code above returns data like this:

enter image description here

I want to get only the job->position and create an alias just like this: enter image description here

I can actually achieve the return in the above image using withCount but I don't think it is the right way to do it.

public function getAllJobOrder()
{
    $results = JobOrder::withCount(['job AS position' => function ($q) {
            $q->select('position');
        }])->get();
    return $results;
}

Is there any other way than using withCount?

Upvotes: 0

Views: 198

Answers (1)

Jinal Somaiya
Jinal Somaiya

Reputation: 1971

try this:

controller

public function getAllJobOrder()
{
    $results = JobOrder::with('job')->get();
    foreach($results as $result){
       $result->position = $result->job->position;
       unset($result->job);
    } 
    return $results;
}

Upvotes: 2

Related Questions