Laravel One to many relation with custom primary key not working
11,473
Solution 1
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.
Solution 2
you have to set this in you Category model
public $incrementing = false;
Author by
themightysapien
Updated on May 25, 2022Comments
-
themightysapien almost 2 years
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 triedCategories::find(15)->adventures()
-
The Alpha almost 10 yearsYes, I believe that because we do silly mistakes (I did myself), you should have took a break and needed to restart after a break with fresh brain. When things go wrong and couldn't find a solution, just take a break, it helps :-)
-
The Alpha almost 10 yearsI've switched from
CI
and one day I've wasted 3 hours to find out a bug and it was that, my redirect wasn't showing anything on the screen but I found it on the other day, it was that, I didn't usereturn
keyword with redirect, it had to be likereturn Redirect(...)
instead ofredirect::(...)
. It took some time to change the practice that I used inCI
. All the best :-) -
Sébastien NOBILI about 3 yearsSame issue for me. This fixes the issue, thanks.