I have two models "Aliments" and "AlimentCategories" , the logic is that 1 food can belong to N "AlimentCategories"
I have the models generated in this way
namespace App;
use Illuminate\Database\Eloquent\Model;
class Aliments extends Model
{
protected $fillable = [
'name', 'description', 'category_id'
];
public function category()
{
$this->hasMany(AlimentCategories::class);
}
the other model
namespace App;
use Illuminate\Database\Eloquent\Model;
class AlimentCategories extends Model
{
protected $fillable = [
'aliment_id','category_id','name','enabled'
];
public function aliments()
{
return $this->hasMany(Aliments::class);
}
I'm not sure if the relationship should be HasMany in both models, or hasMany and belongsTo in the other model.
The error I get when running it from tinker is the following
$categories->foods; Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'aliments.aliment_categories_id' in 'where clause' (SQL: select * from
aliments
wherealiments
.alim ent_categories_id
= 1 andaliments
.aliment_categories_id
is not null)'
The Laravel representation of the relationship
1:N
is with the methodshasMany()
YbelongsTo()
If we go to the relationships one to many section we can check that
EXAMPLE
The following code explains that inside the model class
Post
we have a methodcomments()
to indicate that a post can have many commentsNow in the following code snippet, we have the inverse representation of the
Given the above, your model
Aliments
should have a methodcategories
is plural to represent that a food can have many categoriesAnd in your model
AlimentCategories
there should be a singular method like this, to identify its category of a food