![](/img/trans.png)
[英]Pagination with Slim Framework and Laravel's Eloquent ORM
[英]intersection and pagination in Eloquent ORM
大家好,我有3張桌子:
具有以下屬性的名為content的表:
id
name
table_type_id
release_date
popularity
另一個名為content_genres的表,具有以下屬性:
content_id
genres_id
另一個具有以下屬性的表,稱為genres :
id
name
每個內容可以具有多種類型,一種類型可以具有多種內容。( 多對多 )
好的,直到這里是不同表的定義,現在我正在嘗試進行查詢以搜索具有genre_id = 1和同時genre_id = 2的內容
在postgresql中,這很容易:
SELECT content.id
FROM content INNER JOIN content_genres ON content.id =content_genres.content_id
WHERE content_genres.`genres_id`= 1
INTERSECT
SELECT content.id
FROM content INNER JOIN content_genres ON content.id =content_genres.content_id
WHERE content_genres.`genres_id`= 2
;
我進行一個查詢,再進行另一個查詢,然后進行交集以獲取具有genre_id 1和2的內容
但是當我試圖雄辯地編寫相同的查詢時,我遇到了一些問題:
查詢1:
$content1=$this->content::join('content_genres','content_genres.content_id','=','content.id')
->with('genres')
->where('content_genres.genres_id',1)
->where('content.table_type_id',1)
//->whereYear('release_date',2017)
->select('content.id','content.name','content.popularity')
->orderBy('popularity','desc')->get();
查詢2:
$content2=$this->content::join('content_genres','content_genres.content_id','=','content.id')
->with('genres')
->where('content_genres.genres_id',2)
->where('content.table_type_id',1)
//->whereYear('release_date',2017)
->select('content.id','content.name','content.popularity')
->orderBy('popularity','desc')->get();
路口:
$final_result=$content1->intersect($content2);
好的,我們以這種方式看到的圖像能夠交叉,但我有一些問題:
當我想進行手動分頁時,我不知道如何計算將要有交點的元素,然后限制交點的結果。
例:
查詢1的結果數:
18950
查詢2的結果數:
22650
相交的結果數
3457
這非常慢,因為我不能說將查詢1限制為100個結果,將查詢2限制為100個結果,然后進行相交,所以我不能這樣做,因為相交的結果數不會總是相同,因此出於這個原因,我如何在不加載query1和query2的所有結果的情況下,對交點進行手動分頁,說我想對20個結果中的交點進行分頁?
最后一件事是我整周都遇到的大問題。
您轉到此頁面,然后在年份中不輸入任何內容,在類型中選擇兩個隨機類型。 您如何看到該交叉點的分頁始終為20,這並不取決於交叉點是否有更多結果,或者始終沒有,這始終是20。而且我很確定它們沒有從db中全部加載結果。
好結果:
多虧了答案,正確的方法如下:
$this->content::join('content_genres as g1','g1.content_id','=','content.id')
->join('content_genres as g2','g2.content_id','=','content.id')
->where('g1.genres_id', 1)
->where('g2.genres_id', 2)
它對我有用,我可以選擇其他選項,但是我有很多對很多的關系,因為我的content_genres是數據透視表,但是我認為我也是有效的。
您應該合並兩個查詢。 我看到了兩種方法。
1)兩次加入content_genres
:
$this->content::join('content_genres as g1','g1.content_id','=','content.id')
->join('content_genres as g2','g2.content_id','=','content.id')
->where('g1.genres_id', 1)
->where('g2.genres_id', 2)
2)使用whereHas()
:
$this->content::whereHas('content_genres', function($query) {
$query->where('genres_id', 1)
})->whereHas('content_genres', function($query) {
$query->where('genres_id', 2)
})
這需要一個關系:content→ HasMany
→content_genres
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.