Search code examples
phpmysqllaravelrelationships

Laravel not looking at relationships


I have 2 simple tables in my DB but cannot get laravel to recognise a relationship between the 2. Im fairly new to the laravel game so i may be completely missing something but from looking at guides I seem to have everything there.

Schema::create('pagetextgroup', function($table)
    {
        $table->increments('id');
        $table->string('name');
    });

That table should have many of pagetext table:

    Schema::create('pagetext', function($table)
    {
        $table->increments('id');
        $table->integer('pagetextgroup_id');
        $table->string('placeholder');
        $table->text('text');
        $table->timestamps();
    });

the models:

class PageTextGroup extends Eloquent {

  protected $table = 'pagetextgroup';

  public $timestamps = false;

  public function pageText()
  {
    return $this->hasMany('PageText');
  }

}


class PageText extends Eloquent {

  protected $table = 'pagetext';

  public function pagetextgroup()
  {
    return $this->belongsTo('PageTextGroup');
  }
}

and then in my routes I have the following:

$groupName = Input::get('groupName');

    $group = PageTextGroup::where('name', '=', $groupName)->first()->pageText();

    var_dump($group, DB::getQueryLog());

I have seeded data in the db which matches correctly but for some reason i cannot get laravel to recognise this. am i completely missing something here? there is only 1 query being fired and that is the initial select on the pagetextgroup table.

array(3) {
["query"]=>
string(54) "select * from `pagetextgroup` where `name` = ? limit 1"
["bindings"]=>
array(1) {
  [0]=>
  string(11) "our_service"
}
["time"]=>
float(0.23)
}

any help on this matter would be much appreciated. thanks in advance


Solution

  • try this:

    $group = PageTextGroup::where('name', '=', $groupName)->first()->pageText;
    

    as per the docs the relationships are set as attributes of the returned object, not methods:

    http://laravel.com/docs/eloquent

    class Post extends Eloquent {
    
        public function comments()
        {
            return $this->hasMany('Comment');
        }
    
    }
    
    
    $comments = Post::find(1)->comments;