【问题标题】:How to query all users from database and it's related data?如何从数据库中查询所有用户及其相关数据?
【发布时间】:2015-02-18 16:22:59
【问题描述】:

从任何表返回数据都非常简单。 比方说:

  • 我想以 json 格式从我的 user 表中检索数据。
  • 我可以简单地做到这一点。 return Response::json(User::all());

但是,如果我想从我的用户表 and ALL 中以 json 格式返回 related 数据,该怎么办。

我该怎么做? 是否有任何 Laravel 机制可以帮助我做到这一点? 是否有任何 php 函数可以做到这一点?

如果你们有任何这方面的经验,并愿意分享,请随意。

感谢您的宝贵时间。 :)

【问题讨论】:

标签: php mysql json laravel laravel-4


【解决方案1】:

试试看

Users::with("userinfo")->get()->toJson();

toJson() 提供 JSON 响应。

【讨论】:

    【解决方案2】:

    您可以使用with() 方法预先加载关系:

    return Response::json(User::with('address', 'phones')->get());
    

    但是,您必须手动指定所有关系(即您必须指定“地址”和“电话”)。据我所知,没有内置的方式来以编程方式确定关系。

    编辑

    您应该能够链接with() 调用,或者在一个with() 调用中指定所有关系。以下语句应该都是等价的:

    // chaining with statements
    return Response::json(User::with('address')->with('phones')->get());
    
    // passing all relationships as strings
    return Response::json(User::with('address', 'phones')->get());
    
    // passing in array of all relationships
    return Response::json(User::with(array('address', 'phones'))->get());
    

    另外,要传入的关系名称是定义该关系的函数的名称。所以,如果你有以下课程:

    class User extends Eloquent
    {
        public function distributor()
        {
            return $this->hasOne('Distributor');
        }
    
        public function download()
        {
            return $this->hasOne('Download');
        }
    
        public function log()
        {
            return $this->hasOne('Log');
        }
    }
    

    您的电话如下所示:

    return Response::json(User::with('distributor', 'download', 'log')->get());
    

    【讨论】:

    • 1- 我将all() 替换为get() return Response::json(User::with('address', 'phones')->get());,因为我们不能这样做all() 函数。
    • 2- 出于某种原因,在with 函数中,它不会让我链接另一个关系。当我这样做时它起作用了return Response::json(User::with('Distributor')->get());
    • 3- 当我这样做时它不起作用return Response::json(User::with('Distributor','Download','Log')->get());
    • @iggy 我已根据您的 cmets 更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多