I'm using Laravel with Eloquent. In my example i have 3 tables: image, user and post. What i want to achieve is that the image can belong to a exactly one user and/or exactly one post.
So i think the tables should be like this:
Image
------------
id
image_name
user
------------
id
name
image_id
post
------------
id
text
image_id
I tried to use the following relations:
- image: belongsTo -> user
- image: belongsTo -> post
- user: hasOne -> image
- post: hasOne -> image
But when i do $user->image()->save(someImageObject);
i get the error that the column user_id
is unknown on the image
table which is correct. So i thought that i maybe mis-understand the relations and need to flip them so i changed the relations (even when it feels wrong now) on the models to:
- image: hasOne -> user
- image: hasOne -> post
- user: belongsTo -> image
- post: belongsTo -> image
When i do $user->image()->save(someImageObject);
, i get the error that its not possible to call save()
on a BelongsTo
relation. When i create the relation like this: $image->user()->save(theUserObject);
it works fine but this feels/looks weird in code as i want to add an image to a user and not the user to the image.
So is this simply the way to go and is my "this feels weird" feeling wrong? or is there antoher way i should define my relationship?
I also experimented with morph relationships (many-to-many) and this seems to work fine but than i cannot restrict that a user/post has exactly one image. The morph one-to-many relations sounds by name like its exactly what i need but i have no clue how this should work as it has the relation id/type on the image table. When i test around with this relation type, it replaces the type on the image table when i try to link an image to an user AND post (like i actually expected)