mercredi 23 janvier 2019

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire