Search code examples
phplaraveleloquentlaravel-5eager-loading

Laravel 5.2 EagerLoading relationship returns null


I'm upgrading to Laravel 5.2 from 4.2 and running into a weird issues where when I'm using Eager Loading on a relationship, it returns null, but I can call it manually.

Here's my parent model:

namespace App\Models\Hours;

class Hours extends Model {

/**
 * Model Setup
 */
protected $table = 'leave_hours';
protected $primaryKey = 'leave_id';
public $timestamps = false;

/**
  * Relationships
*/
public function hoursStatus()
{
    return $this->belongsTo('App\Models\Hours\HoursStatusType', 'leave_status_code');
}

Here's the HoursStatusType model:

<?php

namespace App\Models\Hours;

use Illuminate\Database\Eloquent\Model;

class HoursStatusType extends Model {

    /**
     * Model Setup
     */
    protected $table = 'leave_status_type';
    protected $primaryKey = 'leave_status_code';
    public $timestamps = false;

    /**
      * Relationships
    */
    public function hours()
    {
        return $this->hasMany('App\Models\Hours\Hours');
    }

}

Basically Hours has PTO requests that has a status (ie. Pending, Approved, etc). HoursStatusType has only 4 rows and it belongs to many of the Hours request.

I'm doing a big request on the Hours like:

$requests = Hours::with('hoursStatus')->get();

foreach($requests as $r){
   print_r($r->hoursStatus);
}

When I try to print this out using a foreach loop, the hoursStatus relationship is blank. HOWEVER, when when I call it without the eager loading, it's fine. The only thing I have changed since upgrading from 4.2 (besides adding namespace) is change the hoursStatus relationship to belongsTo from a hasOne. Another couple of posts mentioned that changing it should fix it. Not so much.

Am I missing something? Thanks!


Solution

  • You should add public $incrementing = false; to your models setup, when the PK is not an autoincrementing int.