与Laravel的关系?

时间:2014-02-13 10:25:49

标签: laravel laravel-4 eloquent

结构:

**galleries**

id
location
open_to_public

**pictures**
id
title
published

**gallery_picture**
gallery_id
picture_id

型号:

class Galleries extends Eloquent {

protected $table = 'galleries';

public function pictures(){

    return $this->belongsToMany('pictures', 'gallery_picture', 'gallery_id', 'picture_id');

}

我和照片上面的模型相同。

我的问题是,我传入了一张图片ID,然后我需要获取所有属于传入图片ID图片的图片。

到目前为止,我有:

Pictures::with('galleries')->whereId($id)->get();

但这只会返回一张图片。

1 个答案:

答案 0 :(得分:3)

与昨天提出的问题类似,合并集合的所有hasMany对象是Laravel尚未开箱即用的。你需要编写自己的循环:

// we'll eventually have all pictures here
$pictures = new \Illuminate\Database\Eloquent\Collection;

// get all galleries of the given picture
$galleries = Picture::find($id)->galleries;

// iterate through the galleries and add their pictures to our large set
foreach ($galleries as $gallery) {
    $pictures->merge($gallery->pictures);
}

如果它不是belongsToMany关系,而只是Gallery hasMany PicturePicture belongsTo Gallery那么一行代码就可以了:

$pictures = Picture::find($id)->gallery->pictures;

但在这种情况下,给定的图片必须有一个它所属的图库。