2017-06-05 75 views
0

查詢轉換數組我無法傳遞第一個查詢集合將其轉換爲數組。這裏是我的控制器無法通過使用WhereIn

$memberfilters = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id') 
     ->select('member_profiles.id','member_profiles.last_name','member_profiles.first_name','member_profiles.middle_name','member_profiles.name_ext','member_profiles.birthday','member_profiles.encoded_by')    
     ->addSelect(DB::raw('membership_histories.profile_id, membership_histories.log_reason, max(membership_histories.effective_date) as date, membership_histories.membership_type, membership_histories.country_name, membership_histories.sub_region_name'))  
     ->orderBy('member_profiles.last_name','ASC') 
     ->where('membership_histories.country_name', 'Philippines')   
     ->groupBy('membership_histories.profile_id')  
     ->orderBy('date', 'desc') 
     ->get(); 

    $members = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id') 
     ->whereIn('member_profiles.id', $memberfilters->toArray()) 
     ->get(); 

我將申請更多的地方在第二查詢$成員方法,這就是爲什麼我一直在使用,其中將它傳遞到那裏。有了這個邏輯,我得到了我的刀片觀點


@Alexey Mezenin 沒有結果 '0' 當我使用->whereIn('member_profiles.id', $memberfilters->pluck('id')),我得到這個錯誤

ErrorException在ComputeAge.php線13: 試圖讓非對象

的屬性這是我的ComputeAge.php

namespace App\Library; 
use App\MemberProfile; 
use DateTime; 

class ComputeAge 
{ 
// Compute age based on given birthday. 
public static function show($id) 
{ 
    $from = new DateTime(MemberProfile::find($id)->birthday); 
    $to = new DateTime('today'); 
    $age = $from->diff($to)->y; 

    return $age; 
} 
} 
+0

呃..好..嘗試'var_dump'(或者甚至更好'dd')你的'$ memberfilters' ...感覺就像那個變量不僅包含id .. –

+0

Hi @BagusTesa我怎麼寫再次在控制器中?我在哪裏添加dd –

+0

嗨@RodneyZanoria,對於遲到的答案感到抱歉,看起來@AlexeyMezenin已經直接指出了你正確的方向。實際上,我想在確定' - > get()'MemberProfile'後的查詢結果。 –

回答

1

您可以pluck()解決您的第一個問題像阿列克謝回答。針對您的年齡計算問題。你可以利用碳來做到這一點。

<?php 

namespace App\Library; 

use Carbon\Carbon; 
use App\MemberProfile; 

class ComputeAge 
{ 
    public static function show($id) 
    { 
     $user = MemberProfile::findOrFail($id); 
     $age = $user->birthday->diffInYears(Carbon::now(), false); 
     return $age; 
    } 
} 

如果你的生日場不是碳的一個實例,那麼做這個。

$age = Carbon::parse($user->birthday)->diffInYears(Carbon::now(), false); 

如果你不需要在未來生日值負值,那麼你可以叫diffInYears()

0

使用pluck(),例如:

->whereIn('member_profiles.id', $memberfilters->pluck('id')) // Or member_profiles.id instead of id 
+0

這有效,但我不得不在我的控制器中註釋掉一行,因爲它給了我這個錯誤,「ComputeAge.php中的ErrorException:第13行:嘗試獲取非對象的屬性」。 ComputeAge.php是我的文件之一,以獲得年齡。我已經更新了它的內容,以便您檢查我是否有權訪問該文件 –

+0

@RodneyZanoria如果在這裏出現錯誤'MemberProfile :: find($ id)'這只是表示在數據庫中沒有ID = $ id的配置文件。 –

+0

在ComputeAge.php文件中發現錯誤,因爲它說它是非對象。你知道我怎麼能解決這個問題。我粘貼我的ComputeAge.php上面的 –