2015-02-08 92 views
0

嗨,我正在使用Laravel,並從數據庫表中提取登錄的用戶收藏夾。雖然我看到的是我從CMS API獲取的文章,但我也在提取已登錄的用戶收藏夾,但我想檢查用戶是否已經贊成這篇文章,但是獲取了收藏夾並檢查UID是否存在在數組中,如果是這樣,我會輸出一個不同的樣式圖標。所以,我想我會通過我的數據作爲一個數組,然後使用PHP函數in_array但是我得到這個錯誤:Laravel將數據傳遞給Array(),然後檢查in_array是否拋出錯誤

Argument 1 passed to Illuminate\Database\Grammar::columnize() 
must be of the type array, string given 

這是怎麼了檢索我的數據:

//fetch article from cms 
$item = $this->client->fetchPage($id); 
$favourites = Auth::user()->favourites()->get("article_uid")->toArray(); 

,然後在我的視圖

@if (in_array($item->uid, $favourites)) 
     Already a favourite 
@else 
{{Form::open(['action'=>['[email protected]',$item->UID]])}} 
    <button type="submit" class="btn btn-danger"><span class="icon-remove-user"></span>Select Favourite</button> 
{{Form::close()}} 
@endif 

我的陣列被輸出爲這樣:

array(3) { 
    [0] = > array(6) { 
     ["id"] = > string(1)"1" ["user_id"] = > string(1)"1" ["article_uid"] = > string(14)"testb" ["deleted_at"] = > NULL["created_at"] = > string(20)"-0001-11-30 00:00:00" ["updated_at"] = > string(20)"-0001-11-30 00:00:00" 
    }[1] = > array(6) { 
     ["id"] = > string(1)"2" ["user_id"] = > string(1)"1" ["article_uid"] = > string(6)"test" ["deleted_at"] = > NULL["created_at"] = > string(20)"-0001-11-30 00:00:00" ["updated_at"] = > string(20)"-0001-11-30 00:00:00" 
    }[2] = > array(6) { 
     ["id"] = > string(1)"3" ["user_id"] = > string(1)"1" ["aritlce_uid"] = > string(18)"testb" ["deleted_at"] = > NULL["created_at"] = > string(19)"2015-02-08 11:25:32" ["updated_at"] = > string(19)"2015-02-08 11:25:32" 
    } 
} 

理想情況下,我想檢查article_uid$favourites陣列中的$item->uid。然而,我得到這個錯誤,我不知道我做錯了什麼,我認爲它是因爲我的數組比PHP.net上的標準文檔更復雜。在將其傳遞給視圖或其他方法之前,我需要簡化它嗎?有任何想法嗎?

回答

2

如果你只需要ID作爲一個數組,使用lists()

$favourites = Auth::user()->favourites()->lists("article_uid"); 

通過您收到的錯誤是由你傳遞一個字符串get()造成的事實的方式。需要傳遞的陣列(即使它只是一列):

$favourites = Auth::user()->favourites()->get(["article_uid"])->toArray(); 
+0

感謝,這解決了錯誤和陣列陣列輸出作爲這樣:'陣列(3){[0] =>串(14) 「testb」[1] => string(6)「testb」[2] => string(18)「testc」}'我沒有改變'in_array'方法,但仍然會輸出add favorite按鈕事件在數組中 – 001221 2015-02-08 12:03:33

+0

你能回顯'$ item-> uid'以確保它保持正確的值嗎? – lukasgeiter 2015-02-08 12:05:40

+0

啊應該是$ item-> UID。謝謝! – 001221 2015-02-08 12:08:32