【问题标题】:Laravel return model relationships in JSONLaravel 在 JSON 中返回模型关系
【发布时间】:2017-11-23 04:04:10
【问题描述】:

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

【问题讨论】:

    标签: php json laravel laravel-5


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 好的,它可以工作。但如果我使用 with,该模型也可以在没有客户/订阅/federationDiscipline 的情况下获得 CustomerSubscription。我可以和两者一起使用吗?
      • 您当然可以同时使用两者,但是,我会将查询更改为Customer::with("subscription")-&gt;...,因为您正在寻找特定客户。无需直接查询数据透视表。
      【解决方案3】:

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

      您想改用-&gt;with。

      在你的情况下-&gt;with('subscription','federationDiscipline')

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

      【讨论】:

      • 好的,它工作。但如果我使用 with,该模型也可以在没有客户/订阅/federationDiscipline 的情况下获得 CustomerSubscription。我可以和两者一起使用吗?
      • 是的,你可以同时使用。
      猜你喜欢
      • 1970-01-01
      • 2020-11-06
      • 2015-04-18
      • 1970-01-01
      • 2022-08-05
      • 2014-11-06
      • 2014-10-15
      • 2013-07-04
      • 2014-03-25
      相关资源
      最近更新 更多