dounangqie4819 2017-06-20 14:33
浏览 475
已采纳

Laravel在JSON中返回模型关系

When I try to return model relationships in JSON, I don't see the relationship fields. That's my query:

$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;

That's my result:

[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
  }

I don't see the subscription's and the customer's relationship field. The result of query should return JSON to AJAX

  • 写回答

3条回答 默认 最新

  • duanquanzhi5560 2017-06-20 14:38
    关注

    Using ->has only acts as a where condition, it doesn't load that relation in to your result set.

    You want to use ->with instead.

    In your case ->with('subscription','federationDiscipline')

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?