laravel-5eloquentrelationship

Laravel 5.3 belongsTo relation on same table shows no result


I'd like to make a relationship on the same table but I'm not sure it's possible...

I have a table jobs with the fields id, name and parent_id. I want to get some jobs and their parent (and their own parent if they have one, etc.).

Here's my model:

class Job extends Model
{
    public function jobParent()
    {
        return $this->belongsTo('App\Job', 'parent_id');
    }
}

In my controller I do that:

$select = Job::take(10)
               ->with('jobParent')
               ->get();

I displayed the queries and I can see the one for the relationship:

select * from jobs where id in (?, ?, ?)

I have 3 parents for my 10 jobs so it seems right but it returns parent: null for each of my jobs...

Do you see what I'm missing?


I added this to my request because I want also the parent of the parent:

->with(['jobParent' => function($query) {
    $query->with('jobParent');   
}]);

I can see the two queries so it does works, it just doesn't display!

select * from jobs where id in (?, ?, ?)

select * from jobs where id in (?, ?)

I output my results this way:

$return = [
    'success' => 1,
    'totalCount' => $totalCount,
    'nextOffset' => $offset+$nb,
    'jobs' => $jobs
];
$code = 200;
return response()->json($return, $code);

Which gives me this:

{
  "success": 1,
  "totalCount": 10706,
  "nextOffset": 10,
  "jobs": [
    {
      "name": "xxx",
      "parent_id": 15,
      "job_parent": null
    }, ...

I tried to do a foreach of my jobs and a var_dump($job->jobParent) but it says NULL as well...

I just don't get why it doesn't store the results...


Solution

  • I figured it out : job.id is a string, I casted it in my model and it works fine :

    protected $casts = ['id' => 'string'];