2017-02-13 92 views
3

我想創建類似於SQL子查詢的別名,所以我可以像使用純SQL字段一樣使用它。例如,我有3個表格:user,user_commentsuser_comment_answers。如果我想獲得的所有答案,當前用戶的評論的數量,我會做這樣的事情:在Laravel Query Builder中創建一個子查詢別名

SELECT 
    COUNT(*) as comment_answers_count 
    FROM user_comment_answers 
    WHERE user_comment_id IN (SELECT id FROM user_comments WHERE user_id = :id) 

現在我要讓Laravel將此視爲user表的平坦區域,所以我可以簡單地做這樣的東西:

echo Auth::user()->comment_answer_count 

或類似這樣的

$popularUsers = User::where('comment_answer_count', '>=', 100) 

我怎樣才能在Laravel 5.4實現這一目標?

+0

鑑於此鏈接希望這將有助於 http://itsolutionstuff.com/post/laravel-how-to-make-subquery-in -select-statementexample.html –

+0

@recoverymen謝謝,但我知道原始查詢。我想要的是在SQL表或模型的某個地方封裝這個子查詢,並像別的普通SQL字段一樣通過別名來使用它。 –

+0

對不起,我不清楚你想實現什麼.. –

回答

0

用這樣的SQL View創建結束:

CREATE VIEW user_with_comments AS 
SELECT user.*, (
    SELECT 
    COUNT(*) 
    FROM user_comment_answers 
    WHERE user_comment_id IN (SELECT id FROM user_comments WHERE user_id = user.id) 
) as comment_answers_count 
FROM user 

我想這甚至有可能超載雄辯方法從一個表來讀取和寫入到另一個,因爲這個特殊的SQL視圖是隻讀的,但對我來說只讀訪問是不夠的,所以我剛剛建立了另一種模式UserWithComments終於可以使用它像

$popularUsers = UserWithComments::where('comment_answer_count', '>=', 100) 
2

嘗試

$users = Auth::withCount('comments')->get(); 

現在所有用戶都具有comments_count財產

foreach($users as $user) { 
    echo $user->comments_count; 
} 

假設你定義在UserComment模型之間的關係。

更新

根據你的第一個評論,你想要的是一個訪問

public function getCommentAnswerCountAttribute($value) { 
    //define your query here 
} 

此處瞭解詳情:https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

希望這給你找到你的解決方案

的提示
+0

其實,這是獲得'comments_count',而不是'comment_answer_count'的方式。表'user_comment_answers'與'user'表沒有直接的關係,所以這個方法不會工作。但是,這只是一個例子,我的實際案例有更復雜的查詢方式。 –

+0

檢查我的更新。 – EddyTheDove

+0

好點,這解決了部分任務。我仍然不能在'where'子句中使用'comment_answer_count',但我可以簡單地從模型中訪問它。 –