2017-06-20 6 views
0

JSONでモデルリレーションシップを返そうとすると、リレーションシップフィールドが表示されません。私の結果ですJSONのLaravelリターンモデルリレーション

$customer_subscriptions = CustomerSubscription::has("customer") 
       ->has("subscription") 
       ->has("federationDiscipline") 
       ->where("customer_id", "=", $customer_id) 
       ->whereHas("subscription", function($query) use($company_id) { 
        $query->where("company_id", "=", $company_id); 
       }) 
       ->orderBy("start_date", "asc"); 

     return $customer_subscriptions; 

[0]=> 
    array(14) { 
    ["id"]=> 
    int(2) 
    ["customer_id"]=> 
    int(1) 
    ["subscription_id"]=> 
    int(1) 
    ["federation_discipline_id"]=> 
    int(1) 
    ["start_date"]=> 
    string(10) "2017-04-01" 
    ["end_date"]=> 
    string(10) "2017-05-31" 
    ["external_id"]=> 
    NULL 
    ["notes"]=> 
    NULL 
    ["created_user_id"]=> 
    int(1) 
    ["updated_user_id"]=> 
    NULL 
    ["deleted_user_id"]=> 
    NULL 
    ["created_at"]=> 
    string(19) "2017-06-05 07:28:00" 
    ["updated_at"]=> 
    string(19) "2017-06-05 07:28:00" 
    ["deleted_at"]=> 
    NULL 
    } 

私は、サブスクリプションのと顧客の関係フィールドは表示されませんそれは私のクエリです。クエリの結果でJSONがAJAXに返される

答えて

2

->hasを使用すると、where条件としてのみ動作し、結果セットにその関係がロードされません。

代わりに->withを使用します。

あなたの場合

->with('subscription','federationDiscipline')

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

+0

[OK]を、それが動作します。しかし、私と一緒に使うと、モデルはcustomer/subscription/federationDisciplineなしでCustomerSubscriptionを得ることができます。と一緒に使うことができますか? – Mintendo

+0

はい、両方を使用できます。 –

2

結果内の関係を含めてwith()メソッドを使用します。たとえば:

$customer_subscriptions = CustomerSubscription::with("customer")->... 

代わりには、すべてのクエリのためにロードする関係を強制的にモデルにprotected $appends = [...]属性を使用します。しかし、これは、モデルが使用されているすべてのクエリに影響を与えます。これは、データベースが毎回それらの関係をクエリするよう強制するためです。

+0

それはうまく動作します。しかし、私と一緒に使うと、モデルはcustomer/subscription/federationDisciplineなしでCustomerSubscriptionを得ることができます。と一緒に使うことができますか? – Mintendo

+0

あなたは確かに両方を使うことができますが、特定の顧客を探しているのでクエリを 'Customer :: with(" subscription ") - > ...'に変更します。ピボットテーブルを直接照会する必要はありません。 – btl

0

eager loadこれらの関係をjson出力に含める必要があります。現在のクエリは、リレーションがある場合にのみ表示され、リレーションはロードされません。例えば

$customer_subscriptions = CustomerSubscription::has("customer") 
    ->has("subscription") 
    ->has("federationDiscipline") 
    ->where("customer_id", "=", $customer_id) 
    ->whereHas("subscription", function($query) use($company_id) { 
     $query->where("company_id", "=", $company_id); 
    }) 
    ->orderBy("start_date", "asc") 
    ->with('customer'); // <--- Eager loading the customer 

return $customer_subscriptions; 

    return $customer_subscriptions;