Laravel 在 JSON 中返回模型关系

Min*_*ndo 2 php json laravel laravel-5

当我尝试以 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");

        return $customer_subscriptions;
Run Code Online (Sandbox Code Playgroud)

这是我的结果:

[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
  }
Run Code Online (Sandbox Code Playgroud)

我没有看到订阅和客户的关系字段。查询结果应返回 JSON 到 AJAX

Bri*_*laz 5

使用->has只充当一个WHERE条件,它不加载关系到您的结果集。

你想->with改用。

在你的情况下 ->with('subscription','federationDiscipline')

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