【问题标题】:Laravel 4 collection only returning first rowLaravel 4 集合只返回第一行
【发布时间】: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 直到显示所有图像。

重复示例:

http://paste.laravel.com/18uy

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    你搞错了关系。

    class Advertisement extends Eloquent{
    ...
        public function images(){
            return $this->belongsToMany('Image', 'advertisements_images', 'adv_id', 'img_id')->withTimestamps();
        }
    ...
    }
    

    class Image extends Eloquent{
    ...
    public function advertisements(){
        return $this->belongsToMany('Advertisement', 'advertisements_images', 'img_id', 'adv_id')->withTimestamps();
    }
    

    您写错的是它们所属的模型:Image->belongsToMany('Advertisement')Advertisement->belongsToMany('Image')。试着看看这是否足以解决它......其余的对我来说似乎很好

    【讨论】:

    • 好的,现在试试。
    • @VladimirJelovac...我经历过,我知道痛苦;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多