Reputation: 8369
I am trying to implement one to many relation in laravel My tables have custom primary key name not id
I have set $primartKey
attribute as well but the relations doesnot seem to work.
activities
|act_ID|act_acc_ID|.........
categories
|acc_ID|.......
Here are my Models
class Adventure extends \Eloquent {
/**
* @var string $table the name of the table
*/
protected $table = 'activities';
/**
* @var string $primaryKey the primary key of the table
*/
protected $primaryKey = 'act_ID';
/**
* @var bool timestamps updated_at and created_at columns flag
*/
public $timestamps = false;
/**
*
*/
public function category(){
$this->belongsTo('Category','act_acc_ID');
}
}
class Category extends \Eloquent {
/**
* @var string $table the name of the table
*/
protected $table = 'categories';
/**
* @var string $primaryKey the primary key of the table
*/
protected $primaryKey = 'acc_ID';
/**
* @var bool timestamps updated_at and created_at columns flag
*/
public $timestamps = false;
public function adventures(){
$this->hasMany('Adventure','act_acc_ID');
}
}
Now when ever i try to access categories from adventure or adventures from categories i get
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
What am i doing wrong here ??
There are plenty adventures whose category is 15 so i try
I try Categories::find(15)->adventures
also tried Categories::find(15)->adventures()
Upvotes: 3
Views: 13100
Reputation: 391
you have to set this in you Category model
public $incrementing = false;
Upvotes: 3
Reputation: 146191
You didn't use return
keyword, it should be something like this:
public function category(){
return $this->belongsTo('Category','act_acc_ID');
}
public function adventures(){
return $this->hasMany('Adventure','act_acc_ID');
}
Add the return
keyword in both relationship methods.
Upvotes: 4