简体   繁体   English

在laravel中组合查询结果

[英]Combining query results in laravel

On my website, users can upload images and attach tags to those images. 在我的网站上,用户可以上传图像并在这些图像上附加标签。

I've got an images table,a tag table and an images_tag pivot table. 我有一个图像表,一个标记表和一个images_tag数据透视表。

Images can have many tags, and tags can belong to many images. 图像可以具有许多标签,并且标签可以属于许多图像。

I want to be able to generate a list of all the tags a user has used in his/her images. 我希望能够生成用户在其图像中使用过的所有标签的列表。

$imageIDs = Images::where('created_by', Auth::user()->id)->lists('id');

So this would create a list of all the image IDs that a user has upload. 因此,这将创建用户已上传的所有图像ID的列表。

What I want is essentially "foreach $imageIDs, check the images_tag table and for every match go to the tags table and get me back the tagname value." 我想要的基本上是“查找$ imageIDs,检查images_tag表,每次匹配都转到tags表,并让我找回tagname值。”

But I have no idea how I'd do that. 但是我不知道该怎么做。

Maybe a foreach then use the merge method on all the results? 也许foreach然后在所有结果上使用merge方法? Any help would be appreciated! 任何帮助,将不胜感激!

What you could do is this. 您能做的就是这个。

class Tag extends Model
{
    public function images()
    {
        return $this->belongsToMany(Image::class);
    }
}

class SomeController
{
    public function someMethod()
    {
        $tags = Tag::with(['images' => function ($image) {
            return $image->where('created_by', Auth::user()->id);
        }])->select('id', 'tagname')->get();
        // these are your $tags 
    }
}

You should not use a query inside foreach() . 您不应在foreach()使用查询。 Then it would result N+1 problem . 则将导致N + 1问题 What you instead do is eager loading using with() statement. 您要做的是急于使用with()语句加载。

You need to use whereHas() to check the relationship: 您需要使用whereHas()来检查关系:

$userTags = Tags::whereHas('images', function($q) {
    $q->where('created_by', auth()->user()->id);
})->get();

Then just pass this data to a view: 然后将这些数据传递给视图:

return view('some.view', compact('userTags'));

And iterate over tags in a view: 并遍历视图中的标签:

@foreach ($userTags as $tag)
    {{ $tag->name }}
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM