Laravel Eloquent如何归还一对多到多个集合

时间:2015-06-13 04:50:51

标签: php eloquent laravel-5

是否有可能基于One-> Many->多种关系获得雄辩的关系?在下面的示例中,我希望获得给定用户的所有gallery_votes。

users
+----+---------------+
| id |  user_name    |
+----+---------------+
|  1 | bob           |
|  2 | sam           |
+----+---------------+

galleries
+----+---------------+-----------+
| id |  gallery_name |  user_id  |
+----+---------------+-----------+
|  1 | Alaska Pics   |        1  |
|  2 | Texas Pics    |        1  |
|  3 | California    |        2  |
|  4 | Cars          |        2  |
+----+---------------+-----------+

gallery_votes
+----+---------------+--------+
| id |  gallery_id   |  vote  |
+----+---------------+--------+
|  1 |           1   |     1  |
|  2 |           1   |     1  |
|  3 |           1   |     1  |
|  4 |           2   |     1  |
+----+---------------+--------+

关系设置如下。

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {{
    ...
    public function galleries()
    {
        return $this->hasMany('App\Gallery');
    }
}

class Gallery extends Model {
    ....
    public function votes()
    {
        return $this->hasMany('App\GalleryVote');
    }

}

$user->galleries返回一组关联的图库,以便正常工作。并且$gallery->votes返回一组关联投票,这样也可以正常工作。但是$user->galleries->votes给出了

Undefined property: Illuminate\Database\Eloquent\Collection::$votes on line 1

我正在尝试用直拉拉维尔做什么?或者我是否需要直接编写SQL?

1 个答案:

答案 0 :(得分:2)

"有很多通过"关系为通过中间关系访问远距离关系提供了方便的捷径。

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {{
    ...
    public function galleries()
    {
        return $this->hasMany('App\Gallery');
    }

    public function votes() 
    {
        return $this->hasManyThrough('App\GalleryVote', 'App\Gallery');
    }
}

现在$user->votes将返回该用户的所有投票。请记住,您还需要创建GalleryVote雄辩的模型。

您可以阅读有关此类关系的更多信息,以及documentation中的一些示例用法。