2017-03-08 17 views
0

我很難過這一個。我可以搜索一個ID數組,但我想搜索相反的內容。我有模型與ID列表作爲「with_ids」屬性,並希望搜索類似於mongo數據庫,其中ID是在該ID數組中。 例如使用Laravel 5.4查詢生成器與數組(json序列化)屬性

db.conversations.find({ with_ids: { $in: [id] } }) 

如何做到這一點與Laravel和mysql /雄辯?

$conversations = Conversation::with('messages.user')->where('with_ids', $id)->orWhere('created_by', $id)->get(); 

這是哪裏('with_ids',$ id)我無法弄清楚......任何建議?

爲了進一步闡明: 我需要找到用戶是否參與其他對話以及他創建的對話。 with_ids是一個json序列化數組f.ex [1,2,23,12]我如何在數組屬性內搜索?

+0

我認爲你的查詢應該按照它的方式工作。它返回什麼? – EddyTheDove

+0

空白數組...沒有任何對話:: with('messages.user') - > where('with_ids',$ id) - > get(); – IamLasse

+0

哦等等。 'with_ids'在哪裏?在對話或消息中? – EddyTheDove

回答

0

不知道我明白。你有沒有試過whereIn();

$conversations = Conversation::with('messages.user') 
->whereIn('with_ids', [$id]) 
->orWhere('created_by', $id) 
->get(); 

編輯

$conversations = Conversation::with('messages.user', function($query) { 
    $query->where('id', $id); // user_id ? 
}) 
->orWhere('created_by', $id) 
->get(); 
+0

我需要它的另一種方式。我有一個id,我需要檢查它是否存在於id爲「with_ids」的列表中,我需要查找用戶是否參與了其他對話以及他創建的對話。例如with_ids是用戶標識的列表。 with_ids是一個json序列化數組f.ex [1,2,23,12]我如何在數組屬性中搜索? – IamLasse

+0

你至少試了一下。請做,讓我們看看。 – EddyTheDove

0

MUCH挖後,我終於找到了解決辦法。 whereRaw查詢中的FIND_IN_SET完成了任務。如果有其他人遇到這個問題,希望它有幫助。

這不是漂亮,因爲某種原因需要報價被剝離出來

Conversation::where('created_by', $id)->orWhereRaw("FIND_IN_SET(?, REPLACE(REPLACE(REPLACE(with_ids, '\"', ''), '[', ''), ']','')) > 0", $id)->get() 

這是最終的查詢得到聚集通話情況:用戶創建或爲的一部分。