Reputation: 2998
This should be really simple, but I can't seem to figure it out.
There are two tables:
`images`
|- `id`
|- `path`
|- `name`
`foods`
|- `id`
|- `image_id`
And two models:
class Image extends Eloquent {
public function food() {
return $this->belongsToMany('Food');
}
}
class Food extends Eloquent {
public function image() {
return $this->hasOne('Image');
}
}
The idea is that each food
has a single image
associated with it through the image_id
column in its foods
table row. A single image
can be associated to multiple foods.
I'd like to be able to do something like this in a controller:
$food = Food::with('image')->find(1);
...but, of course, I get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'images.food_id' in 'where clause' (SQL: select * from images
where images
.food_id
in (1))
...because Eloquent would like each image
to have a food_id
. But, of course, image
s don't have food_id
s. Foods have image_id
s.
Please help a frustrated coder out. :)
Thank you!
EDIT:
Thank you so much, duellsy.
I have updated my models to this:
class Image extends Eloquent {
public function food() {
return $this->hasMany('Food');
}
}
class Food extends Eloquent {
public function image() {
return $this->belongsTo('Image');
}
}
...and now the Food::with('image')
call works.
I truly don't understand why 'Food' belongs to 'Image' though... perhaps someone might be able to explain why the syntax doesn't match the grammer here?
Upvotes: 1
Views: 231
Reputation: 8577
While it grammatically sounds like it should be a hasOne
relationship, the way your data is setup is actually a belongsTo
relationship.
i.e., the food table has the foreign key, so it belongs to
whatever that foreign key is pointing to
Additionally, the inverse is true for the images model, it doesn't belong to
anything since there's no foreign key or pivot tables involved. Instead, it has many
foods
The grammar / syntax seems a bit backwards in your case purely because in most systems you would expect that a food item has many images, not the other way around. It can get tricky often, which is why it's always worth forgetting about the model names and just thinking about who has the foreign keys.
Upvotes: 2