Laravel 4在哪里和很多很多

时间:2014-06-12 11:30:11

标签: php laravel relation where-in

我有一个标签系统,您可以在其中为照片和用户添加标签。

我有一个功能,用户可以添加自己喜欢的标签,并根据这些标签选择图像

但我的问题我是一个非常大的初学者用PHP和laravel,我不知道如何将值传递给whereIn函数

模型

public function tag()
    {
        return $this->belongsToMany('Tag', 'users_tag');
    }

控制器

// get the logged in user
        $user = $this->user->find(Auth::user()->id);

        // get tags relation
        $userTags = $user->tag->toArray();

        // select photos based on user tags
        $photos = Photo::whereHas('tag', function($q) use ($userTags)
        {
            $q->whereIn('id', $userTags);

        })->paginate(13);


        $trendyTags = $this->tag->trendyTags();

        $this->layout->title = trans('tag.favorite');
        $this->layout->content = View::make('main::favoritetags')
                                ->with('user', $user)
                                ->with('photos', $photos)
                                ->with('trendyTags', $trendyTags);

当我通过时我得到一个错误

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array 

比我尝试使用array_flatten()来清理我的数组

// get the logged in user
        $user = $this->user->find(Auth::user()->id);

        // get tags relation
        $userTags =array_flatten($user->tag->toArray());

        // select photos based on user tags
        $photos = Photo::whereHas('tag', function($q) use ($userTags)
        {
            $q->whereIn('id', $userTags);

        })->paginate(13);


        $trendyTags = $this->tag->trendyTags();

        $this->layout->title = trans('tag.favorite');
        $this->layout->content = View::make('main::favoritetags')
                                ->with('user', $user)
                                ->with('photos', $photos)
                                ->with('trendyTags', $trendyTags);

这种方式有效,但没有返回正确的标签。

请问有人可以帮我一把吗?

1 个答案:

答案 0 :(得分:4)

当然,我会提出一些建议。

要获取用户模型,您只需使用$user = Auth::user()

要使用whereIn(),它需要一维用户ID数组。 toArray()函数将返回一个包含所有用户及其属性的关联数组,因此它无法正常工作。要获得所需内容,您应该使用lists('id')

最后一件真正帮助我的事情是当你建立一个将要返回一组对象(hasManybelongsToMany())的关系时,建立关系名称plurual,所以在这种情况下,您可以将tag()函数修改为tags()

所有这一点,这应该适合你。

// get the logged in user
$user = Auth::user();

// get tags relation
$userTags = $user->tags()->lists('id');

// select photos based on user tags
$photos = Photo::whereHas('tags', function($q) use ($userTags)
{
    $q->whereIn('id', $userTags);

})->paginate(13);

$trendyTags = $this->tags->trendyTags();

$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
                        ->with('user', $user)
                        ->with('photos', $photos)
                        ->with('trendyTags', $trendyTags);

我建议修改你的关系......虽然不是很重要。

public function tags()
{
    return $this->belongsToMany('Tag', 'users_tag');
}
相关问题