Answer the question
In order to leave comments, you need to log in
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
<?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');
}
}
Image
from a model Article
using relations, for example:<?php
foreach (Article::find($id)->images as $image)
{
var_dump($image->url);
}
hasManyThrough
:class Article extends Eloquent {
public function images()
{
return $this->hasManyThrough('Image', 'ArticleImage');
}
}
hasManyThrough
it does not take into account the relations registered in other models and does not allow to register the relationship between the models Image
and 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
. articleImage
we 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
}
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);
}
images
. Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question