Laravel 5.2 |查询多对多 [英] Laravel 5.2 | query many to many to one
问题描述
目前,我正在开展一个多域名和语言项目,其中视频被重复使用不同的标题和描述。
Currently I am working on a multi domain and language project where videos are reused with different titles and description.
我与这个问题相关的表与关系像
My tables that are relevant to this question with relations look like
posts >- videos >- videos_tags -< tags
id id id id
domain_id video_id
video_id tag_id
当然,我已经创建了模型:Post,Video和Tag与所有必需的关系。
Of course I have created the models: Post, Video and Tag with all the required relationships.
我正在尝试的事情是通过我的标签模型获取所有的帖子,维护分页()功能。
The thing I am trying is to get all the posts by my Tag model and maintaining the pagination() functionality.
我可以通过视频模型获取链接到帖子的所有标签。但是,当我尝试逆向的方式时,我似乎并没有保持分页()功能。我已经尝试了很多,但似乎找不到正确的解决方案。
I am able to get all tags linked to a Post through a Video model. However when I am trying an inverse way I don't seem to keep the pagination() functionality. I have tried a lot but can't seem to find the right solution.
最近(我想)我一直在使用这段代码:
The closest (I think) I have been with this piece of code:
// App\Models\Tag
public function posts()
{
$posts = [];
foreach ($this->videos as $video)
{
foreach ($video->posts as $post)
{
if (!array_key_exists($post->id, $posts)) $posts[$post->id] = $post;
}
}
return \Illuminate\Database\Eloquent\Collection::make($posts);
}
我在寻求答案时遇到的任何建议或文章都受到欢迎: )
Any suggestions or articles I have missed during my quest for the answer are welcome :)
推荐答案
直接问了这个问题后,我有一个尤里卡时刻,找到了解决方案。这样做的方法不是通过标签模型获取Post模型,而是通过Post模型本身。
Directly after asking this question I had an eureka moment and found the solution. A way to do this is not by getting the Post models by the Tag model but through the Post model itself.
这就是我所做的:
// App\Models\Tag
public function posts()
{
return Post
::select('posts.*')
->join('videos', 'posts.video_id', '=', 'videos.id')
->join('videos_tags', 'videos.id', '=', 'videos_tags.video_id')
->join('tags', 'videos_tags.tag_id', '=', 'tags.id')
->where('tags.id', $this->id);
}
这解决了查询多对多到一个问题关系和维护征集功能之前执行查询。
This solves the problem of querying a many to many to one relationship and maintaining eloquents functionalities before the query is executed.
这篇关于Laravel 5.2 |查询多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!