使用多態關係likeable
,我已經在likeable_items
表中設置了authors
和books
作爲likeable_type
。Laravel 5.3 - 在一個查詢中提取多態表的數據?
下面是型號:
class Like extends Model {
public function likeable(){
return $this->morphTo();
}
}
class Author extends Model {
public function likes(){
return $this->morphMany('App\Like', 'likeable');
}
}
class Book extends Model {
public function likes(){
return $this->morphMany('App\Like', 'likeable');
}
}
我想用一個高效的查詢到拉他們都在各自的數據,10分頁,這樣的事情不工作(我評論的代碼以顯示每一步需要什麼)。
$likeableData =
DB::table('likeable_items')
// We want to fetch additional data depending on likeable_type
->select(['books.title', 'books.author_name', 'book_counts.like_count']) // when likeable_type = 'book'
->select(['authors.name', 'authors.country', 'authors.age', 'author_counts.like_count']) // when likeable_type = 'author'
->leftJoin('books', 'books.id', '=', 'likeable_items.likeable_id') // when likeable_type = 'book'
->leftJoin('book_counts', 'book_counts.book_id', '=', 'likeable_items.likeable_id') // when likeable_type = 'book'
->leftJoin('author_counts', 'author_counts.author_id', '=', 'likeable_items.likeable_id') // when likeable_type = 'author'
// We want to have distinct results, based on unique id of book/author
->distinct()
// We want to order by the highest like_count, regardlress of likeable_type
->orderBy('book_counts.like_count', 'desc') // order by highest like_count when likeable_type = 'book'
->orderBy('author_counts.like_count', 'desc') // order by highest like_count when likeable_type = 'author_counts'
// We want to paginate the mixed results
->paginate(10);
return $likeableData;
如何,我可以得到不同的結果背部的最高喜歡author
/book
通過likes_count
,各自的數據,10分頁?
UPDATE:
下面是表模式:
Table: likeable_items
- id
- likeable_id (book_id or author_id)
- likeable_type (book or author)
Table: books
- id
- title
- author_name
Table: book_counts
- book_id
- like_count
Table: authors
- id
- name
- country
- age
Table: author_counts
- author_id
- like_count
你看過你當前方法的sql結果嗎?這對我來說看起來效率並不高效 –
這就是我發佈的原因,因爲我不知道如何做我在評論中的作爲一個有效的查詢:) – Wonka
您的'Like'模型是否使用'likeable_items'表?你可以發佈你正在查詢的3個表格的模式嗎? –