How to build relationships between Eloquent models in Laravel 5?

We have the following table:
articles
id
article_images
article_id
image_id
images
id
 url


and models:
<?php
class Article extends Eloquent {
 public function articleImages()
{
 return $this--->hasMany('ArticleImage', 'article_id', 'id');
}
}

class ArticleImage extends Eloquent {
 public function article()
{
 return $this->'s belongsto('Article', 'article_id', 'id');
}
 public function image()
{
 return $this->'s belongsto('Image', 'image_id', 'id');
}
}

class Image extends Eloquent {
 public function articleImages()
{
 return $this->hasOne('ArticleImage', 'image_id', 'id');
}
}


Objective: to obtain a list of images Image of model Articleusing relationship, for example:
<?php
 foreach (Article::find($id)--->images as $image)
{
var_dump($image->url);
 }


Begs the relationship hasManyThrough:
class Article extends Eloquent {
 public function images()
{
 return $this->hasManyThrough('Image', 'ArticleImage');
}
}

But hasManyThrough does not take into account the relationship spelled out in other models and does not allow to specify the relation between the models Image and ArticleImage (or rather, allows, but partially) and trying joint table article_images.id = images.idwhere you can only select images.id.

If you try to withdraw via articleImage get the error:
foreach (Article::find($id)->articleImages as $articleImage)
{
 var_dump($articleImage->image->url); // ErrorException: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
 }

Google proposes to use this method:
class ArticleImage extends Eloquent {
 public function image()
{
 return $this->'s belongsto('Image', 'image_id', 'id');
}
 public function getImageUrl()
{
 return $this->image->url;
}
}
foreach (Article::find($id)->articleImages as $articleImage)
{
var_dump($articleImage->imageUrl);
}

To put it mildly is not convenient because I need to write a getter for each field in the table images.

Maybe there's some option to correctly configure hasManyThrough I missed? I do not want to change the field names in the database or to write getters.
September 19th 19 at 00:20
1 answer
September 19th 19 at 00:22
Solution
class Article extends Eloquent{
 public function images(){
 return $this->belongsToMany('Image', 'article_images', 'article_id', 'image_id');
}
}
In this case, it joint article_images.id = images.image_id, I wrote - mustafa.McCullou commented on September 19th 19 at 00:25
Would read more carefully =) I Wrote belongsToMany. - emiliano15 commented on September 19th 19 at 00:28
Oh, sorry, eyes are blurry already. It really works, thanks for the help. - mustafa.McCullou commented on September 19th 19 at 00:31

Find more questions by tags PHPLaravelORM