Lookup table between two models Having 3 SQL tables
images
- id
galleries
- id
images_galleries
-images_id
-galleries_id
How can I relate in the Galeries model the hasMany images?
I have this but doesn't feel like being the correct thing to do:
class Gallery extends Model
{
protected $table = 'galleries';
protected $guarded = ['id'];
public function images ()
{
return $this->hasMany('App\Image);
}
}
This is a BelongsToMany relationship (documentation ):
public function images ()
{
return $this->belongsToMany('App\Image', 'images_galleries', 'galleries_id', 'images_id');
}
images_galleries is pivot table
so you need use belongsToMany
The joining table also needs to be the singular form of both tables it's joining, and in alphabetical order, so it should be image_gallery
Thanks @staudenmeir @newbie360 and @Cronix for the prompt replies! I'm still very fresh to laravel and dind't understand the mechanics of belongsToMany
About your reply @Cronix ... you are talking about the table names or the ids?
Is this ok?
images
- id
galleries
- id
image_gallery
- id_image
- id_gallery
I would just have two table for that instead of three.
galleries
- id
- description
images
-id
-image
-gallery_id
Unless of course the image can belong to multiple galleries.
if image not belongsToMany galleries
i will
galleries
- id
- description
images (PK = gallery_id+image)
-gallery_id
-image
-image_order
@Cronix Thanks mate!
@Tray2 & @newbie360 yup ... images will belong to multiple galleries as well as they might be used on other parts of the application... so having a belongsToMany on the galleries part will leave the db open to more flexibility for the future.
Thanks everybody for the swift and detailed and suggestive answers... as usual ... this community is awesome! :)
@penaf You're welcome! If you have it working now, please mark your thread as solved.
@Cronix : by the way, you most surelly can help me out with this one (don't know if I should ask a new question instead of asking here...)
On my GalleryController.php I have this:
public function data()
{
$resultados = Galery::all();
foreach ($resultados as $resultado){
$resultado->multimedia_count = Galery::images()->withCount('image_id');
}
return DataTables::of($resultados)->make(true);
}
I'm messing up big time am I not?
Please sign in or create an account to participate in this conversation.