Reputation: 290
I have many to many relationship and what I am trying is to get all rows from the pivot table based on a certain advertisement id.
My tables:
advertisements table
images table
advertisements_images
My models:
Image.php
class Image extends Eloquent
{
protected $table = "images";
/**
*
* @return type
*/
public function advertisements()
{
return $this->belongsToMany('Image', 'advertisements_images', 'img_id', 'adv_id')->withTimestamps();
}
public function setNameAttribute($value)
{
$this->attributes['name'] = $value . date('YmdHis');
}
}
Advertisement.php
class Advertisement extends Eloquent
{
protected $table = "advertisements";
public static $sluggable = array(
'build_from' => 'title',
'save_to' => 'alias'
);
public function images()
{
return $this->belongsToMany('Advertisement', 'advertisements_images', 'adv_id', 'img_id')->withTimestamps();
}
public function categories()
{
return $this->belongsToMany('Advertisement', 'advertisements_categories', 'adv_id', 'cat_id')->withTimestamps();
}
Method inside controller
private function selectMainImage($id)
{
$images = \Advertisement::find($id)->images;
$temp = array(array());
$i = 0;
foreach ($images as $image) {
$temp[$i]['id'] = $image->id;
$temp[$i]['name'] = $image->name;
$temp[$i]['url'] = \MyThumbnails::get($image->id, "125x125");
$i++;
}
$data = array(
'title' => 'Odaberite glavnu sliku',
'id' => $id,
'images' => $temp
);
$this->generateView('layout.backend.advertisement.main-image', $data);
}
This method should return a view with all 6 images, instead it returns only the first image. When I do a var_dump() on a collection I get this which returns only the first row: http://paste.laravel.com/18up If I create duplicate advertisements in the database the collection will return first and second row. And if I do it again will return row + 1 untill all images are displayed.
Example of duplicate:
Upvotes: 0
Views: 926
Reputation: 2647
You got the relationships wrong.
class Advertisement extends Eloquent{
...
public function images(){
return $this->belongsToMany('Image', 'advertisements_images', 'adv_id', 'img_id')->withTimestamps();
}
...
}
And
class Image extends Eloquent{
...
public function advertisements(){
return $this->belongsToMany('Advertisement', 'advertisements_images', 'img_id', 'adv_id')->withTimestamps();
}
What you wrote wrong is the Model they belong to: Image->belongsToMany('Advertisement')
and Advertisement->belongsToMany('Image')
. Try to see if this is enough to fix it... the rest seems good to me
Upvotes: 2