【发布时间】:2013-12-01 14:34:54
【问题描述】:
我有多对多的关系,我正在尝试根据某个广告 ID 从数据透视表中获取所有行。
我的桌子:
广告表
图片表
广告图片
我的模特:
图片.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');
}
}
广告.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();
}
控制器内部的方法
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);
}
这个方法应该返回一个包含所有 6 个图像的视图,而不是只返回第一个图像。 当我对集合执行 var_dump() 时,我得到这个只返回第一行:http://paste.laravel.com/18up 如果我在数据库中创建重复广告,则集合将返回第一行和第二行。如果我再做一次,将返回 row + 1 直到显示所有图像。
重复示例:
【问题讨论】:
标签: laravel laravel-4 eloquent