php - Laravel返回JSON中的模型关系

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

最佳答案

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

您想改用->with

在你的情况下->with('subscription','federationDiscipline')
https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

关于php - Laravel返回JSON中的模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655969/

相关文章:

php - 如何阻止用户根据每个 ID 的 jquery 计数删除表中的所有 tr?

javascript - 将 JavaScript 日期发送到 PHP 后端的最佳格式是什么?

php - 我可以将 Facebook 的 hiphop 与 Zend Framework、cakephp、symfony 等框架一起使用吗

JavaScript 访问对象

javascript - 使用 Mix 在 Laravel 中未检测到 VueJs

使用 x10hosting 连接 PHP MySQL 数据库

python - 使用列表中的字符串动态创建嵌套的字典

json - 有没有办法扩展 angular.json 中的配置?

Laravel Socialite 无法在实时服务器上运行,只能在本地计算机上运行

php - 尝试使用 cmd 在 Laravel 5.6 中播种时出现语法错误,意外的 ','