Reputation: 301
I am trying to get products according to categories by using Laravel Relationships.
Category names are stored in terms table and in products table, I have added term_id column.
This is what I have done so far in Term model-
public function products(){
return $this->hasMany('shopist\Models\Product');
}
And in my Controller-
public function products()
{
$pro = term::where('term_id',2)->first();
$pro->products;
}
But I am not getting any results.
Upvotes: 2
Views: 165
Reputation: 9
try
public function products()
{
return Term::where('term_id',2)->first();
}
or if you have a Product Model
public function products()
{
return Product::where('term_id',2)->first();
}
Upvotes: 0
Reputation: 719
Please correct your relation in Term model by following this-
public function products()
{
return $this->hasMany('shopist\Models\Product', 'term_id', 'term_id'); // foreign key and local key should be defined
}
You have to define the foreign key and local key in the relation because you are not following the recommended laravel conventions for the primary key column names.
So it's necessary to tell the method that what keys need to be used as a relation.
Upvotes: 2