hodale
hodale

Reputation: 747

hasMany returns null

I'm on laravel 4.2, trying to get an objects associative relation yet for some reason I am getting null.

Models:

        class Keg extends Eloquent {

          protected $fillable = ['beer_distribution_id', 'status', 'keg_size'];

          public function beer_distribution()
          {
            return $this->belongsTo('BeerDistribution');
          }

        }

        class BeerDistribution extends Eloquent {

            protected $fillable = ['beer_id', 'distributor_id'];

            public function kegs()
            {
                return $this->hasMany('Keg');
            }

        }

My Query:

        $distirbution = Keg::find($tap->keg_id)->beer_distribution

This query returns null: I know the keg object is found and I know that the object has the beer_distribution_id.

I tried specifying the foreign key in the model like so:

        class Keg extends Eloquent {

          protected $fillable = ['beer_distribution_id', 'status', 'keg_size'];

          public function beer_distribution()
          {
            return $this->belongsTo('BeerDistribution', 'beer_distribution_id');
          }

        }

I thought that might be necessary since the Model is camel case.

I know this is super simple, and I am in fact querying many relations succesfully through out my application, but for some reason this one is not working. Any thoughts on what I might be missing?

Upvotes: 1

Views: 244

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153150

The problem is the function name of the relationship. Laravel expects it to be in camel case: beerDistribution().

Change that and you should be good. (You don't have to specify the foreign key, Laravel will convert camelCase to snake_case)

Upvotes: 1

Related Questions