0

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?

4
  • If you want to always select single column then add select('position') with your relationship. Commented Jan 24, 2019 at 6:57
  • correct me if I'm wrong, using select requires the id column. which means it would return 2 columns. Commented Jan 24, 2019 at 6:59
  • Yes you are right. need id column always. Commented Jan 24, 2019 at 7:01
  • well I only need 1 column and not return a nested array Commented Jan 24, 2019 at 7:05

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.