Laravel在JSON中返回模型关系

时间:2017-06-20 14:33:09

标签: 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;

这是我的结果:

[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

3 个答案:

答案 0 :(得分:4)

使用->has仅作为where条件,它不会将该关系加载到结果集中。

您想改用->with

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

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

答案 1 :(得分:3)

使用with()方法在结果中包含关系。例如:

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

或者,使用模型上的protected $appends = [...]属性强制为每个查询加载关系。但请记住,这会影响使用模型的所有地方的查询,因为它会强制数据库每次都查询这些关系。

答案 2 :(得分:1)

您必须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;