T
T
Tesla2015-03-02 12:17:04
ORM
Tesla, 2015-03-02 12:17:04

How to build relationships between Eloquent Laravel 5 models?

We have the following tables:

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->belongsTo('Article', 'article_id', 'id');
  }
  public function image()
  {
    return $this->belongsTo('Image', 'image_id', 'id');
  }
}

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

Task: get a list of images Imagefrom a model Articleusing relations, 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 hasManyThroughit does not take into account the relations registered in other models and does not allow to register the relationship between the models Imageand ArticleImage(more precisely, it allows, but partially) and tries to join tables by article_images.id = images.id, where you can only select images.id.
If we try to output through articleImagewe get an 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 suggests using this method:
class ArticleImage extends Eloquent {
  public function image()
  {
    return $this->belongsTo('Image', 'image_id', 'id');
  }
  public function getImageUrl()
  {
    return $this->image->url;
  }
}
foreach (Article::find($id)->articleImages as $articleImage)
{
  var_dump($articleImage->imageUrl);
}

Which, to put it mildly, is not convenient, because. it is necessary to prescribe a getter for each field of the table images.
Maybe there is some option to correctly configure hasManyThrough that I missed? I really do not want to change the names of the fields in the database or paint getters.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cha-cha, 2015-03-02
@Tesla

class Article extends Eloquent{
    public function images(){
        return $this->belongsToMany('Image', 'article_images', 'article_id', 'image_id');
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question