【问题标题】:Laravel - Return associated models to jsonLaravel - 将关联模型返回到 json
【发布时间】:2014-03-25 11:37:24
【问题描述】:

我有两个模型,ThreadsLeads

我正在尝试将线程作为 JSON 对象返回,但我得到的只是一个为空的 leads 字段。

线程模型;

public function leads()
{
    return $this->belongsTo('Leads');
}    

领导模型;

public function threads()
{
    return $this->hasMany('Threads');
}

线程控制器;

public function getLead($id=null)
{
    $thread = Threads::thread($id)->with('leads')->get();

    return Response::json($thread)->setCallback(Input::get('callback'));
}

【问题讨论】:

    标签: json laravel associations


    【解决方案1】:

    不要with(),而是尝试load()他们:

    $thread = Threads::thread($id)->load('leads')->get();
    

    另外,关于你的命名的注释:你的Threads 模型的leads() 函数应该被称为lead(),因为Thread 只有一个Lead(这就是你使用belongsTo() 的原因),但这是只是为了便于阅读。

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2015-04-18
      • 2020-11-06
      • 2014-10-15
      相关资源
      最近更新 更多