Laravel从模型belongsToMany关系返回到控制器的结果


Laravel getting results from model belongsToMany relationship back to controller

我使用的是Laravel 5和Eloquent,我有3个表设置:

photos
+----+---------------+------------------+
| id |  photo_name   |  photo_location  |
+----+---------------+------------------+
|  1 | kittens.jpg   | C:'kittens.jpg   |
|  2 | puppies.jpg   | C:'puppies.jpg   |
|  3 | airplanes.jpg | C:'airplanes.jpg |
|  4 | trains.jpg    | C:'trains.jpg    |
+----+---------------+------------------+
photo_set (pivot table)
+------------+----------+
| set_id     | photo_id |
+------------+----------+
|          1 |        1 |
|          1 |        2 |
|          2 |        3 |
|          2 |        4 |
+------------+----------+
sets
+----+----------------+
| id |  description   |
+----+----------------+
|  1 | cute animals   |
|  2 | transportation |
+----+----------------+

我在我的photossets模型中创建了一个belongsToMany关系,将它们连接在一起。

class Photo extends Model {
    public function sets()
    {
        return $this->belongsToMany('App'Set');
    }
}

class Set extends Model {
    public function photos()
    {
        return $this->belongsToMany('App'Photo');
    }
}

然而,我试图在我的控制器中引用$Sets->photos()模型函数,以便给定一组id=1,我可以返回每一行[C:'kittens.jpg,C:'puppies.jpg]photo_location值,但我不知道如何访问它。

同样,我可以在视图中"sort"访问这些信息:

@foreach($sets as $set)
    {{$set->images}}
@endforeach

,但它看起来只迭代一次,并返回必要信息的json(?),虽然我不确定如何将其解析为常规HTML。

简而言之,从控制器和视图访问这个数据(photo_location)有问题

使用Collection::lists()

$locations = Set::find(1)->photos->lists('photo_location');

它将返回一个数组['C:'kittens.jpg', 'C:'puppies.jpg']

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html method_lists

在你的控制器中试试:

$result = PhotoSet::where('set_id', $set_id)
          ->with('sets')
          ->with('photos')
          ->get();
$photo_location = $result->photos->photo_location;

这里PhotoSet是photo_set表的模型,因为它是一个数据透视表我们可以从它访问sets和photos表